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

场景:有三个线程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毫秒。

 
  1. public class ThreadTest1 {

  2. // T1、T2、T3三个线程顺序执行

  3. public static void main(String[] args) {

  4.     Thread t1 = new Thread(new Work(null));

  5.     Thread t2 = new Thread(new Work(t1));

  6.     Thread t3 = new Thread(new Work(t2));

  7.     t1.start();

  8.     t2.start();

  9.     t3.start();

  10.  
  11. }

  12. static class Work implements Runnable {

  13.     private Thread beforeThread;

  14.     public Work(Thread beforeThread) {

  15.         this.beforeThread = beforeThread;

  16.     }

  17.     public void run() {

  18.         if (beforeThread != null) {

  19.             try {

  20.                 beforeThread.join();

  21.                 System.out.println("thread start:" + Thread.currentThread().getName());

  22.             } catch (InterruptedException e) {

  23.                 e.printStackTrace();

  24.             }

  25.         } else {

  26.             System.out.println("thread start:" + Thread.currentThread().getName());

  27.         }

  28.     }

  29. }

  30. }

2.使用CountDownLatch

     CountDownLatch(闭锁)是一个很有用的工具类,利用它我们可以拦截一个或多个线程使其在某个条件成熟后再执行。它的内部提供了一个计数器,在构造闭锁时必须指定计数器的初始值,且计数器的初始值必须大于0。另外它还提供了一个countDown方法来操作计数器的值,每调用一次countDown方法计数器都会减1,直到计数器的值减为0时就代表条件已成熟,所有因调用await方法而阻塞的线程都会被唤醒。这就是CountDownLatch的内部机制,看起来很简单,无非就是阻塞一部分线程让其在达到某个条件之后再执行。

 
  1. public class ThreadTest2 {

  2.  
  3. // T1、T2、T3三个线程顺序执行

  4. public static void main(String[] args) {

  5.     CountDownLatch c0 = new CountDownLatch(0); //计数器为0

  6.     CountDownLatch c1 = new CountDownLatch(1); //计数器为1

  7.     CountDownLatch c2 = new CountDownLatch(1); //计数器为1

  8.  
  9.     Thread t1 = new Thread(new Work(c0, c1));

  10.     //c0为0,t1可以执行。t1的计数器减1

  11.  
  12.     Thread t2 = new Thread(new Work(c1, c2));

  13.     //t1的计数器为0时,t2才能执行。t2的计数器c2减1

  14.  
  15.     Thread t3 = new Thread(new Work(c2, c2));

  16.     //t2的计数器c2为0时,t3才能执行

  17.  
  18.     t1.start();

  19.     t2.start();

  20.     t3.start();

  21.  
  22. }

  23.  
  24. //定义Work线程类,需要传入开始和结束的CountDownLatch参数

  25. static class Work implements Runnable {

  26.     CountDownLatch c1;

  27.     CountDownLatch c2;

  28.  
  29.     Work(CountDownLatch c1, CountDownLatch c2) {

  30.         super();

  31.         this.c1 = c1;

  32.         this.c2 = c2;

  33.     }

  34.  
  35.     public void run() {

  36.         try {

  37.             c1.await();//前一线程为0才可以执行

  38.             System.out.println("thread start:" + Thread.currentThread().getName());

  39.             c2.countDown();//本线程计数器减少

  40.         } catch (InterruptedException e) {

  41.         }

  42.  
  43.     }

  44. }

  45. }

3.CachedThreadPool

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

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

 
  1.  public class ThreadTest3 {

  2.     // T1、T2、T3三个线程顺序执行

  3.    public static void main(String[] args) {

  4.     FutureTask<Integer> future1= new FutureTask<Integer>(new Work(null));

  5.     Thread t1 = new Thread(future1);

  6.  
  7.     FutureTask<Integer> future2= new FutureTask<Integer>(new Work(future1));

  8.     Thread t2 = new Thread(future2);

  9.  
  10.     FutureTask<Integer> future3= new FutureTask<Integer>(new Work(future2));

  11.     Thread t3 = new Thread(future3);

  12.  
  13.     t1.start();

  14.     t2.start();

  15.     t3.start();

  16. }

  17.  
  18. static class Work  implements Callable<Integer> {

  19.     private FutureTask<Integer> beforeFutureTask;

  20.     public Work(FutureTask<Integer> beforeFutureTask) {

  21.         this.beforeFutureTask = beforeFutureTask;

  22.     }

  23.     public Integer call() throws Exception {

  24.         if (beforeFutureTask != null) {

  25.             Integer result = beforeFutureTask.get();//阻塞等待

  26.             System.out.println("thread start:" + Thread.currentThread().getName());

  27.         } else {

  28.             System.out.println("thread start:" + Thread.currentThread().getName());

  29.         }

  30.         return 0;

  31.     }

  32. }

  33. }

 

4.使用blockingQueue

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

 
  1. public class ThreadTest4 {

  2. // T1、T2、T3三个线程顺序执行

  3. public static void main(String[] args) {

  4.     //blockingQueue保证顺序

  5.     BlockingQueue<Thread> blockingQueue = new LinkedBlockingQueue<Thread>();

  6.     Thread t1 = new Thread(new Work());

  7.     Thread t2 = new Thread(new Work());

  8.     Thread t3 = new Thread(new Work());

  9.  
  10.     blockingQueue.add(t1);

  11.     blockingQueue.add(t2);

  12.     blockingQueue.add(t3);

  13.  
  14.     for (int i=0;i<3;i++) {

  15.         Thread t = null;

  16.         try {

  17.             t = blockingQueue.take();

  18.         } catch (InterruptedException e) {

  19.             e.printStackTrace();

  20.         }

  21.         t.start();

  22.         //检测线程是否还活着

  23.         while (t.isAlive());

  24.     }

  25. }

  26.  
  27. static class Work implements Runnable {

  28.  
  29.     public void run() {

  30.         System.out.println("thread start:" + Thread.currentThread().getName());

  31.     }

  32. }

  33. }

5.使用单个线程池

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

 
  1. public class ThreadTest5 {

  2.  
  3. public static void main(String[] args) throws InterruptedException {

  4.     final Thread t1 = new Thread(new Runnable() {

  5.         public void run() {

  6.             System.out.println(Thread.currentThread().getName() + " run 1");

  7.         }

  8.     }, "T1");

  9.     final Thread t2 = new Thread(new Runnable() {

  10.         public void run() {

  11.             System.out.println(Thread.currentThread().getName() + " run 2");

  12.             try {

  13.                 t1.join(10);

  14.             } catch (InterruptedException e) {

  15.                 e.printStackTrace();

  16.             }

  17.         }

  18.     }, "T2");

  19.     final Thread t3 = new Thread(new Runnable() {

  20.         public void run() {

  21.             System.out.println(Thread.currentThread().getName() + " run 3");

  22.             try {

  23.                 t2.join(10);

  24.             } catch (InterruptedException e) {

  25.                 e.printStackTrace();

  26.             }

  27.         }

  28.     }, "T3");

  29.  
  30.     //使用 单个任务的线程池来实现。保证线程的依次执行

  31.     ExecutorService executor = Executors.newSingleThreadExecutor();

  32.     executor.submit(t1);

  33.     executor.submit(t2);

  34.     executor.submit(t3);

  35.     executor.shutdown();

  36. }

  37. }

  38.  
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用线程同步的方法来实现三个线程的顺序执行,比如使用信号量或互斥锁。 具体实现方法如下: 1. 创建三个线程,分别执行任务 A、B、C。 2. 使用信号量或互斥锁来同步三个线程的执行。在任务 A 执行完后,释放信号量或解锁互斥锁,使得任务 B 可以执行;在任务 B 执行完后,同样释放信号量或解锁互斥锁,使得任务 C 可以执行。 3. 在主线程中等待三个子线程全部执行完毕,然后结束程序。 下面是一个简单的示例代码: ```c #include <stdio.h> #include <pthread.h> #include <semaphore.h> sem_t sem1, sem2; void *threadA(void *arg) { printf("Thread A\n"); sem_post(&sem1); // 释放信号量 sem1 pthread_exit(NULL); } void *threadB(void *arg) { sem_wait(&sem1); // 等待信号量 sem1 printf("Thread B\n"); sem_post(&sem2); // 释放信号量 sem2 pthread_exit(NULL); } void *threadC(void *arg) { sem_wait(&sem2); // 等待信号量 sem2 printf("Thread C\n"); pthread_exit(NULL); } int main() { sem_init(&sem1, 0, 0); // 初始化信号量 sem1 sem_init(&sem2, 0, 0); // 初始化信号量 sem2 pthread_t tid1, tid2, tid3; pthread_create(&tid1, NULL, threadA, NULL); pthread_create(&tid2, NULL, threadB, NULL); pthread_create(&tid3, NULL, threadC, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_join(tid3, NULL); sem_destroy(&sem1); // 销毁信号量 sem1 sem_destroy(&sem2); // 销毁信号量 sem2 return 0; } ``` 在上面的示例代码中,信号量 sem1 和 sem2 分别用来同步任务 A、B 和任务 B、C 的执行线程 A 执行完后释放信号量 sem1,线程 B 等待信号量 sem1,线程 B 执行完后释放信号量 sem2,线程 C 等待信号量 sem2。最后,主线程等待三个子线执行完毕后才结束程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值