赞
踩
确保三个线程 T1、T2、T3 按照指定顺序执行有多种方式。以下是其中一些常见的方式:
-
- Thread T1 = new Thread(() -> {
- // 线程 T1 的任务
- });
-
- Thread T2 = new Thread(() -> {
- try {
- T1.join(); // 等待 T1 执行完成
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- // 线程 T2 的任务
- });
-
- Thread T3 = new Thread(() -> {
- try {
- T2.join(); // 等待 T2 执行完成
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- // 线程 T3 的任务
- });
-
- T1.start();
- T2.start();
- T3.start();

- CountDownLatch latch1 = new CountDownLatch(1);
- CountDownLatch latch2 = new CountDownLatch(1);
-
- Thread t1 = new Thread(() -> {
- System.out.println("T1 running.");
- latch1.countDown(); // T1 执行完后释放 latch1
- });
-
- Thread t2 = new Thread(() -> {
- try {
- latch1.await(); // 等待 latch1 的释放
- System.out.println("T2 running.");
- latch2.countDown(); // T2 执行完后释放 latch2
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- });
-
- Thread t3 = new Thread(() -> {
- try {
- latch2.await(); // 等待 latch2 的释放
- System.out.println("T3 running.");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- });
-
- t1.start();
- t2.start();
- t3.start();

- public class Test {
- private static Thread t1;
- private static Thread t2;
- private static Thread t3;
- public static void main(String[] args) {
-
- t1 = new Thread(() -> {
- System.out.println("T1 is running.");
- LockSupport.unpark(t2); // 唤醒线程T2
- });
-
- t2 = new Thread(() -> {
- LockSupport.park(); // 阻塞线程T2
- System.out.println("T2 is running.");
- LockSupport.unpark(t3); // 唤醒线程T3
- });
-
- t3 = new Thread(() -> {
- LockSupport.park(); // 阻塞线程T3
- System.out.println("T3 is running.");
- });
-
-
- t1.start();
- t2.start();
- t3.start();
- }
- }

这些方法都可以用来确保线程按照指定顺序执行。选择其中一种方式取决于你的具体需求和场景。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。