运行时怎么和张老师的运行结果不同啊?求助
package cn_heima_Thread;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
ExecutorService ex=Executors.newCachedThreadPool();
final CountDownLatch countdownlatch=new CountDownLatch(1);
final CountDownLatch countdownlatch1=new CountDownLatch(3);
for(int i=0;i<3;i++){
Runnable runnable=new Runnable(){
public void run(){
System.out.println("线程"+Thread.currentThread().getName()+"开始等待首长发布命令!");
try {
countdownlatch.await();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("线程"+Thread.currentThread().getName()+"收到命令!");
try {
Thread.sleep(new Random().nextInt(10)*1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("线程"+Thread.currentThread().getName()+"已经跑到终点");
countdownlatch1.countDown();
}
};
ex.execute(runnable);
}
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
System.out.println("首长开始发布命令");
countdownlatch.countDown();
System.out.println("首长已经发布!正在等候");
try {
countdownlatch1.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("首长最终收到命令!");
}
}
|