直入主题,代码如下:(不懂评论区评论,当日回复信息)
技术实现关键:计数器(CountDownLatch)
public static void main(String[] args) {
// 新建一个为2的计数器
final CountDownLatch latch = new CountDownLatch(2);
// 新建线程1任务
Thread thread1 = new Thread() {
@Override
public void run() {
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread1启动了!!!");
latch.countDown();
}
};
// 启动线程1
thread1.start();
// 新建线程2任务
Thread thread2 = new Thread() {
@Override
public void run() {
System.out.println("Thread2启动了!!!");
latch.countDown();
}
};
// 启动线程2
thread2.start();
System.out.println("等待两个线程执行结束-------");
try {
// 等待计数器为0
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("两个线程已执行完毕!");
}