如何确保三个线程顺序执行

Java多线程 有ABC 3 个线程,线程C需要等待线程AB执行完成才能执行的实现方式 LockSupport、CountDownLatch、CyclicBarrier 多线程相互等待 阅读详情

三个线程t1、t2、t3。确保三个线程,t1 执行完后 t2 执行,t2 执行完后 t3 执行。

一、使用 CountDownLatch

二、使用 join

thread.join 把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程 A 中调用了线程 B 的 join(),直到线程 B 执行完毕后,才会继续执行线程 A。

public class ThreadTest1 {
	// T1、T2、T3三个线程顺序执行
	public static void main(String[] args) {
		Thread t1 = new Thread(new Work(null));
		Thread t2 = new Thread(new Work(t1));
		Thread t3 = new Thread(new Work(t2));
		t1.start();
		t2.start();
		t3.start();
	}

	static class Work implements Runnable {
		private Thread beforeThread;
		public Work(Thread beforeThread) {
			this.beforeThread = beforeThread;
		}
		public void run() {
			if (beforeThread != null) {
				try {
					beforeThread.join();
					System.out.println("thread start:" + Thread.currentThread().getName());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("thread start:" + Thread.currentThread().getName());
			}
		}
	}
}

三、CachedThreadPool

FutureTask 一个可取消的异步计算。FutureTask 实现了 Future 的基本方法,提空 start cancel 操作,可以查询计算是否已经完成,并且可以获取计算的结果。结果只可以在计算完成之后获取, get 方法会阻塞当计算没有完成的时候,一旦计算已经完成,那么计算就不能再次启动或是取消。

一个 FutureTask 可以用来包装一个 Callable 或是一个 runnable 对象。因为 FurtureTask 实现了 Runnable 方法,所以一个 FutureTask 可以提交(submit)给一个 Excutor 执行(excution)。

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class ThreadTest3 {

	// T1、T2、T3三个线程顺序执行
	public static void main(String[] args) {
		FutureTask<Integer> future1 = new FutureTask<Integer>(new Work(null));
		Thread t1 = new Thread(future1);

		FutureTask<Integer> future2 = new FutureTask<Integer>(new Work(future1));
		Thread t2 = new Thread(future2);

		FutureTask<Integer> future3 = new FutureTask<Integer>(new Work(future2));
		Thread t3 = new Thread(future3);

		t1.start();
		t2.start();
		t3.start();
	}

	static class Work implements Callable<Integer> {
		private FutureTask<Integer> beforeFutureTask;

		public Work(FutureTask<Integer> beforeFutureTask) {
			this.beforeFutureTask = beforeFutureTask;
		}

		public Integer call() throws Exception {
			if (beforeFutureTask != null) {
				Integer result = beforeFutureTask.get();//阻塞等待
				System.out.println("thread start:" + Thread.currentThread().getName());
			} else {
				System.out.println("thread start:" + Thread.currentThread().getName());
			}
			return 0;
		}
	}
}

四、使用阻塞队列(BlockingQueue)

阻塞队列(BlockingQueue)是java util.concurrent包下重要的数据结构。BlockingQueue 提供了线程安全的队列访问方式:当阻塞队列进行插入数据时,如果队列已满,线程将会阻塞等待直到队列非满;从阻塞队列取数据时,如果队列已空,线程将会阻塞等待直到队列非空。并发包下很多高级同步类的实现都是基于 BlockingQueue 实现的。

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ThreadTest4 {
	
	// T1、T2、T3三个线程顺序执行
	public static void main(String[] args) {
		//blockingQueue保证顺序
		BlockingQueue<Thread> blockingQueue = new LinkedBlockingQueue<Thread>();
		Thread t1 = new Thread(new Work());
		Thread t2 = new Thread(new Work());
		Thread t3 = new Thread(new Work());

		blockingQueue.add(t1);
		blockingQueue.add(t2);
		blockingQueue.add(t3);

		for (int i = 0; i < 3; i++) {
			Thread t = null;
			try {
				t = blockingQueue.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			t.start();
			//检测线程是否还活着
			while (t.isAlive()) ;
		}
	}

	static class Work implements Runnable {
		public void run() {
			System.out.println("thread start:" + Thread.currentThread().getName());
		}
	}
}

五、使用单个线程池

newSingleThreadExecutor 返回一个包含单线程的 Executor,将多个任务交给此 Executor 时,这个线程处理完一个任务后接着处理下一个任务,若该线程出现异常,将会有一个新的线程来替代。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadTest5 {

	public static void main(String[] args) {
		final Thread t1 = new Thread(new Runnable() {
			public void run() {
				System.out.println(Thread.currentThread().getName() + " run 1");
			}
		}, "T1");
		final Thread t2 = new Thread(new Runnable() {
			public void run() {
				System.out.println(Thread.currentThread().getName() + " run 2");
				try {
					t1.join(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "T2");
		final Thread t3 = new Thread(new Runnable() {
			public void run() {
				System.out.println(Thread.currentThread().getName() + " run 3");
				try {
					t2.join(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "T3");

		//使用 单个任务的线程池来实现。保证线程的依次执行
		ExecutorService executor = Executors.newSingleThreadExecutor();
		executor.submit(t1);
		executor.submit(t2);
		executor.submit(t3);
		executor.shutdown();
	}
}

三个线程轮流打印1-100

六、synchronized关键字实现

public class MyThread1 implements Runnable {

    private static Object lock = new Object();
    private static int count;
    private int no;

    public MyThread1(int no) {
        this.no = no;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (lock) {
                if (count > 100) {
                    break;
                }
                if (count % 3 == this.no) {
                    System.out.println(Thread.currentThread().getName() + "\t" + this.no + "\t" + count);
                    count++;
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new MyThread1(0), "A");
        Thread t2 = new Thread(new MyThread1(1), "B");
        Thread t3 = new Thread(new MyThread1(2), "C");
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
    }
}

七、ReentrantLock实现一

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyThread2 implements Runnable {

    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();
    private static int count;
    private int no;

    public MyThread2(int no) {
        this.no = no;
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();
            if (count > 100) {
                break;
            } else {
                if (count % 3 == this.no) {
                    System.out.println(this.no + "-->" + count);
                    count++;
                } else {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            condition.signalAll();
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new MyThread2(0));
        Thread t2 = new Thread(new MyThread2(1));
        Thread t3 = new Thread(new MyThread2(2));
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
    }
}

八、ReentrantLock 实现二

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Testmain {
    public static void main(String[] args) {

        Alternate an = new Alternate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 33; i++) {
                    an.logA(i);
                }
            }
        }, "A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 33; i++) {
                    an.logB(i);
                }
            }
        }, "B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 33; i++) {
                    an.logC(i);
                    System.out.println("--------------------------------");
                }
            }
        }, "C").start();
    }
}

class Alternate {

    private static int num = 1;
    private int tempA = 0;
    private int tempB = 0;
    private int tempC = 0;
    Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void logA(int total) {
        lock.lock();
        try {
            if (num != 1 && num != (tempA + 3)) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + num + "\t" + total);
            tempA = num;
            num++;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void logB(int total) {
        lock.lock();
        try {
            if (num != 2 && num != (tempB + 3)) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + num + "\t" + total);
            tempB = num;
            num++;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void logC(int total) {
        lock.lock();
        try {
            if (num != 3 && num != (tempC + 3)) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + num + "\t" + total);
            tempC = num;
            num++;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
开启多个线程,如果保证顺序执行,有哪几种实现方式? 哈喽,各位小伙伴们,你们好呀,我是喵手。运营社区:C站/掘金/腾讯云/阿里云/华为云/51CTO(全网同号);欢迎大家常来逛逛,互相学习。 阅读详情

相关推荐

面试官:多个线程执行完毕后,才执行另一个线程,该怎么做?

CountDownLatch 去掉try catch版本 public static void main(String[] args) throws InterruptedException { /** * Thread-1 在路上耗时4秒 * Thread-2 在路上耗时0秒 * Thread-0 在路上耗时4秒 * Thread-2 到达车站了 * Thread-1 到达车站了 * Thread-0 到达车站了 * 老司机,发车 */ CountDownLatch.

小识的博客 2130

如何确保三个线程顺序执行?

场景:有三个线程t1、t2、t3。确保三个线程t1执行完后t2执行,t2执行完成后t3执行。 1.使用join thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。 t.join(); //调用join方法,等待线程t执行完毕 t.join(1000); //等待 t 线程,等待时间是1000毫秒。 public class ThreadTest1...

sushuiyuzhou的专栏 3929

【Java面试题】有三个线程 t1,t2,t3,怎么确保它们按顺序执行?

有三个线程 t1,t2,t3,怎么确保它们按顺序执行

扛麻袋的少年的博客 5242

线程顺序执行的8种方法,最后一种你用过吗?

本文主要介绍了多线程如何执行顺序

张小凡 9975

C# WinForms实战:5分钟用ScottPlot打造专业级示波器界面(附完整代码)

本文详细介绍了如何在C# WinForms应用中,利用ScottPlot.WinForms库快速构建一个专业级的软件示波器界面。通过从环境配置、静态波形绘制到动态数据实时更新的完整实战演示,帮助开发者高效实现高性能的波形显示功能,适用于工业监控、信号分析等多种场景。

weixin_29198045的博客 840

ESP32-S3射频测试与全球认证全栈实践指南

功率谱密度(PSD)和发射功率等级是无线通信设备射频合规的核心基础概念,其物理层原理直接决定自适应测试、阻塞容限及多国认证的通过路径。PSD ≥10 dBm/MHz触发强制性自适应测试,需验证LBT机制与跳频鲁棒性;而16级可编程发射功率等级(-24 dBm至+20 dBm)则为功耗、覆盖与法规平衡提供工程调控维度。该能力广泛应用于低功耗蓝牙IoT终端、智能家居网关及工业无线传感器等场景,尤其在ESP32-S3平台中,需结合eFuse校准、Sigma工具链与QuickTrack认证策略实现从实验室调试到量产

weixin_34945060的博客 299

java三个线程 顺序执行_如何确保三个线程顺序执行

三个线程t1、t2、t3。确保三个线程,t1执行完后t2执行,t2执行完后t3执行。一、使用jointhread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。t.join(); //调用join方法,等待线程t执行完毕t.join(1000); //等待 t 线...

weixin_39646706的博客 1699

使用光流进行 Warp 的流程

光流描述了图像帧中每个像素的运动。前向光流:描述了帧中每个像素在帧中的移动位置。后向光流:描述了帧中每个像素在帧​ 中的移动位置。水平方向的位移(x 方向),即每个像素水平移动了多少像素。垂直方向的位移(y 方向),即每个像素垂直移动了多少像素。使用光流进行 Warp 的流程Warp 是通过光流对图像进行变换的操作,旨在将前一帧的像素根据光流场映射到下一帧的对应位置。Step 1: 计算光流我们首先需要通过光流网络(如 RAFT)来估算两帧之间的光流。我们可以获得前向光流(从帧​ 到帧。

qq_44199605的博客 2110

确保三个线程顺序执行

三个线程T1,T2,T3,如何保证顺序执行? 在多线程中有多种方法让线程按特定顺序执行,你可以用线程类的join()方法在一个线程中启动另一个线程,另外一个线程完成该线程继续执行。为了确保三个线程的顺序你应该先启动最后一个(T3调用T2,T2调用T1),这样T1就会先完成而T3最后完成。 实际上先启动三个线程中哪一个都行, 因为在每个线程的run方法中用join方法限定了三个线程的执行顺序。 public class JoinTest2 { // 1.现在有T1、T2、T3三个线程,你怎样保证T

hahayixiao1的博客 508

禅道18.3版本二开避坑指南:手把手教你扩展自定义报表功能

本文详细介绍了禅道18.3版本的二次开发实践,重点讲解如何扩展自定义报表功能。通过zentaoPHP框架的深度定制,从开发环境搭建到核心数据模型扩展,再到可视化配置和性能优化,手把手教你构建多维报表分析系统,满足企业级项目管理需求。

day7的博客 375

观测器选择与工程实践建议

摘要:永磁同步电机(PMSM)无传感器控制中,观测器选型需综合考虑应用场景、性能需求与成本。消费级(家电、工具)推荐滑模观测器(SMO),成本低、鲁棒性强;工业级(伺服、泵阀)适用扩展卡尔曼滤波器(EKF),精度高但计算复杂;车规级(EPS、主驱动)需混合观测器(SMO+EKF),兼顾全速域性能与可靠性。低速时需高频注入法,IPMSM更适用。SMO易实现但存在抖振,EKF调试复杂。未来趋势是混合架构与AI增强,提升适应性与性能。选型需权衡速度范围、电机类型、处理器能力及成本。

汽车软件开发 150

Java多线程2:确保三个线程顺序执行

前言:三个线程t1、t2、t3。确保三个线程顺序执行,t1执行完后t2执行,t2执行完后t3执行。 1、使用join thread.Join 把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程 B 中调用了线程 A 的 join(),直到线程 A 执行完毕后,才会继续执行线程 B。 public class ThreadTest1 { // T1、T2、T3三个线程顺序执行 public static void main(String[] arg

何哥的博客 2400

STM32F401RCT6最小系统原理图设计

STM32F401RCT6最小系统原理图设计一、主控芯片二、电源电路三、晶振电路三、下载电路四、完整电路图      本文章基于STM32F401RCT6进行最小系统原理图设计,包含主控芯片,电源,晶振电路,下载电路等几部分 一、主控芯片 主控芯片采用STM32F401RCT6,需注意: VBAT在不接电池的情况下需接3.3V,VDDAVREF+需接3.3V,否则会造成芯片供电不正常,无法启动和识别的情况 VDDAVREF+和VCAP1处电容需按照规格书

weixin_43278295的博客 2万+

java线程顺序执行 确保T1, T2, T3三个线程顺序执行

 String threadName = Thread.currentThread().getName();        System.out.println(threadName + " start...");        Thread firstThread = new Thread(new ThreadOne());        Thread secondThread = new Th...

凌岩歌贰拾肆的专栏 818

深度学习部署工程师--8(docker+TensorRT部署到推理+yolo人体检测)下

本文介绍了YOLOv5模型通过TensorRT加速部署的流程。首先需要检查磁盘空间,确保有30GB可用。文章对比了不同推理方式的性能:int8量化+TensorRT可达200FPS,纯TensorRT为166FPS,CUDA为147FPS,CPU为93FPS。重点讲解了将YOLOv5模型导出为ONNX格式的详细步骤,包括修改Detect类的forward方法以移除decode运算,使用git patch批量修改代码,安装必要的依赖库,以及通过onnx-graphsurgeon工具修改ONNX图结构。最终目标

FJN110的博客 499

SAP-ABAP:新手入门篇——从0到1写出你的第一个ABAP Hello World程序并完成调试运行

本文是ABAP开发入门指南,详细介绍如何创建并运行第一个"Hello World"程序。主要内容包括:通过SE38事务码进入ABAP编辑器;创建以Z/Y开头的程序并保存为本地对象;编写简单的WRITE输出语句;完成语法检查、激活和执行流程;以及初步体验调试功能。文章特别强调ABAP开发的规范要求,如程序命名规则、激活与保存的区别等,并提供了详细的步骤说明和常见问题提示,帮助零基础开发者快速上手ABAP编程。

baidu_35680696的博客 488

有三个线程T1,T2,T3,怎么确保它们按顺序执行?

有三个线程T1,T2,T3,怎么确保它们按顺序执行?

m0_51740882的博客 298

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

有三个线程T1,T2,T3,下面方法可以确保它们按顺序执行的有()该线程继续执行

1.先启动最后一个(T3调用T2,T2调用T1) package com.te; public class Testt { static Testt t=new Testt(); class T1 extends Thread{ @Override public void run() { //T3线程中要处理的东西 System.out.println("

哦绝影 9552

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

有三个线程 T1,T2,T3,怎么确保它们按顺序执行?

package com.atguigu.test; public class Test1 { public static void main(String[] args) { ThreadA threadA = new ThreadA(); ThreadB threadB = new ThreadB(threadA); ThreadC threadC = new ThreadC(threadB); threadA.start(); threadB.start(); threa

li237的博客 791

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java面试题之有三个线程 T1,T2,T3,怎么确保它们按顺序执行?

有两种方法: 1.利用线程的join方法 join()方法用于将线程由”并行“变成”串行“.它用于等待其他线程的终止,在当前线程掉用了join()方法,那么当前线程将进入阻塞状态,等到另一个线程结束,当前线程再由阻塞状态转变成就绪状态,等待CPU的使用权。 package com.atguigu.test; public class Test1 { public static void main(String[] args) { ThreadA threadA = new ThreadA();

weixin_43664019的博客 2557

创建三个线程并依次执行

文章目录一、join方法二、线程池 昨天做笔试题的时候遇到一个多线程的问题,需要我们创建三个线程,操作同一个String,并且依次赋值,最后打印。 操作同一个String只需要我们同步或者加锁就可以保证其原子性了,可是如何保证顺序执行呢? 一、join方法 我们来看api文档中的说明,等待本线程死亡。 也就是说,我们在其他线程run方法内部调用本线程的join方法,其他线程必须等待本线程死亡后才能...

白衣 3652
上一篇: 同步问题的解决--锁对象Lock
下一篇: 线程通信的几种方式
JFS_Study
博客等级 码龄6年 363粉丝 359原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JFS_Study

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址