现在有T1、T2、T3三个线程,你怎样保证T2在T1执行完后执行,T3在T2执行完后执行?...

Thread t1 = new Thread(new T1()); 
Thread t2 = new Thread(new T2()); 
Thread t3 = new Thread(new T3());

t1.start(); 
t1.join();

t2.start(); 
t2.join();

t3.start(); 
t3.join();

主要是使用了join()方法

看看jdk的join方法是如何实现的吧

 1 public final synchronized void join(long millis)
 2     throws InterruptedException {
 3         long base = System.currentTimeMillis();
 4         long now = 0;
 5 
 6         if (millis < 0) {
 7             throw new IllegalArgumentException("timeout value is negative");
 8         }
 9 
10         if (millis == 0) {
11             while (isAlive()) {
12                 wait(0);
13             }
14         } else {
15             while (isAlive()) {
16                 long delay = millis - now;
17                 if (delay <= 0) {
18                     break;
19                 }
20                 wait(delay);
21                 now = System.currentTimeMillis() - base;
22             }
23         }
24     }
View Code

 

 

在Java中,为了实现这样的线程同步,可以使用`synchronized`, `wait()`, 和 `notifyAll()` 等并发工具。我们可以创建一个包含共享资源的对象,并利用 `volatile` 关键字防止数据竞争。下面是一个简单的例子: ```java public class ThreadTask { private volatile int result; private final Object lock = new Object(); public void startThreads(int t2Result, int t3Result) { Thread t1 = new Thread(() -> { synchronized (lock) { try { result = Math.max(t2Result, t3Result); System.out.println("T1 got results, result is " + result); // Notify T2 and T3 that result is available lock.notifyAll(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t2 = new Thread(() -> { while (!Thread.currentThread().equals(t1)) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // Simulate a task with random delay for result try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } result = t2Result; // Set your own result }); Thread t3 = new Thread(() -> { while (!Thread.currentThread().equals(t1)) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // Similar to T2, simulate a task try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } result = t3Result; }); t1.start(); t2.start(); t3.start(); // Wait for all threads to finish try { t1.join(); t2.join(); t3.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { ThreadTask task = new ThreadTask(); task.startThreads(10, 20); // Replace with actual values or generate them dynamically } } ``` 在这个例子中,`startThreads`方法启动了三个线程`t1`, `t2`, 和 `t3`。`t1`负责获取并存储结果,然后唤醒等待的`t2`和`t3`。`t2`和`t3`分别模拟延迟任务并在得到通知后设置自己的结果。主线程会等待所有线程完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值