场景:有三个线程t1、t2、t3。确保三个线程t1执行完后t2执行,t2执行完成后t3执行。
方法1:thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
package com.gs.demo1; public class ThreadTest1 { public static void main(String[] args) { Thread t1 = new Thread(new Work(null),"线程t1"); Thread t2 = new Thread(new Work(t1),"线程t2"); Thread t3 = new Thread(new Work(t2),"线程t3"); t1.start(); t2.start(); t3.start(); } static class Work implements Runnable{ private Thread beforeThread; public Work(Thread beforeThread) { this.beforeThread = beforeThread; } @Override public void run() { if(beforeThread!=null) { try { //某线程调用该方法,会让其他线程处于等待状态,让其运行完毕,再执行其他线程. beforeThread.join(); System.out.println("Thread start:"+Thread.currentThread().getName()); }catch(Exception e){ e.printStackTrace(); } }else { System.out.println("Thread start:"+Thread.currentThread().getName()); } } } }
方法2:使用CountDownLatch
CountDownLatch(闭锁)是一个很有用的工具类,利用它我们可以拦截一个或多个线程使其在某个条件成熟后再执行。它的内部提供了一个计数器,在构造闭锁时必须指定计数器的初始值,且计数器的初始值必须大于0。另外它还提供了一个countDown方法来操作计数器的值,每调用一次countDown方法计数器都会减1,直到计数器的值减为0时就代表条件已成熟,所有因调用await方法而阻塞的线程都会被唤醒。这就是CountDownLatch的内部机制,看起来很简单,无非就是阻塞一部分线程让其在达到某个条件之后再执行。
package com.gs.demo2; import java.util.concurrent.CountDownLatch; public class ThreadTest2 { public static void main(String[] args) { CountDownLatch c1 = new CountDownLatch(0);//计数器为0 CountDownLatch c2 = new CountDownLatch(1);//计数器为1 CountDownLatch c3 = new CountDownLatch(1);//计数器为1 Thread t1 = new Thread(new Work(c1, c2),"线程t1"); //c1为0,t1线程可以执行。t1线程的计数器 c2 减1 Thread t2 = new Thread(new Work(c2, c3),"线程t2"); //t1的计数器c2为0时,t2才能执行。t2的计数器c3减1 Thread t3 = new Thread(new Work(c3, c3),"线程t3"); //t3的计数器c3为0时,t3才能执行 t1.start(); t2.start(); t3.start(); } //定义Work线程类,需要传入开始和结束的CountDownLatch参数 static class Work implements Runnable { private CountDownLatch c1; private CountDownLatch c2; public Work(CountDownLatch c1, CountDownLatch c2) { super(); this.c1 = c1; this.c2 = c2; } @Override public void run() { try { //当某个线程调用CountDownLatch对象的await方法时,将会阻塞,直到计数器的值变成0才放行。 c1.await(); System.out.println("thread start:" + Thread.currentThread().getName()); c2.countDown(); //本线程计数器减 1 } catch (InterruptedException e) { e.printStackTrace(); } } } }
参考文献:https://www.cnblogs.com/kaleidoscope/p/9877174.html
原文地址:https://www.cnblogs.com/gshao/p/10527403.html
时间: 2024-11-07 16:15:54