package test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test2 {
public static void main(String[] args) {
ExecutorService service=Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(3);
for(int i=0;i<3;i++){
Runnable runnable=new Runnable(){
@Override
public void run() {
try {
System.out.println("线程:"+Thread.currentThread().getName()+"正在准备接受命令");
cdOrder.await();
System.out.println("线程"+Thread.currentThread().getName()+"已经接受命令");
Thread.sleep((long) (Math.random()*10000));
System.out.println("线程"+Thread.currentThread().getName()+"回应命令处理结果");
} catch (InterruptedException e) {
}
}
};
service.execute(runnable);
}
try {
Thread.sleep((long)(Math.random()*10000));
System.out.println("线程"+Thread.currentThread().getName()+"即将发布命令");
cdOrder.countDown();
System.out.println("线程" + Thread.currentThread().getName() +
"已发送命令,正在等待结果");
cdAnswer.await();
System.out.println("线程" + Thread.currentThread().getName() +
"已收到所有响应结果");
} catch (InterruptedException e) {
e.printStackTrace();
}
service.shutdown();
}
//运动员 百米赛跑 ,首先大家都在等待 中(三个线程在等待接受命令),当吹口号 的人,吹起号声(已发送命令), 完成各自的工作。
}
打印结果
线程:pool-1-thread-1正在准备接受命令
线程:pool-1-thread-3正在准备接受命令
线程:pool-1-thread-2正在准备接受命令
线程main即将发布命令
线程main已发送命令,正在等待结果
线程pool-1-thread-3已经接受命令
线程pool-1-thread-1已经接受命令
线程pool-1-thread-2已经接受命令
线程pool-1-thread-1回应命令处理结果
线程pool-1-thread-2回应命令处理结果
线程pool-1-thread-3回应命令处理结果
package test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
public class Test3 {
final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch=new CountDownLatch(2);//两个工人的协作
Worker worker1=new Worker("zhang san", 5000, latch);
Worker worker2=new Worker("li si", 8000, latch);
worker1.start();//
worker2.start();//
latch.await();//等待所有工人完成工作
System.out.println("all work done at "+sdf.format(new Date()));
}
static class Worker extends Thread{
String workerName;
int workTime;
CountDownLatch latch;
public Worker(String workerName ,int workTime ,CountDownLatch latch){
this.workerName=workerName;
this.workTime=workTime;
this.latch=latch;
}
public void run(){
System.out.println("Worker "+workerName+" do work begin at "+sdf.format(new Date()));
doWork();//工作了
System.out.println("Worker "+workerName+" do work complete at "+sdf.format(new Date()));
latch.countDown();//工人完成工作,计数器减一
}
private void doWork(){
try {
Thread.sleep(workTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
本文探讨了Java并发编程中的线程池、CountDownLatch等工具的使用,通过实例展示了线程之间的协作与命令流程,包括命令的发布、接收与响应处理。
1673

被折叠的 条评论
为什么被折叠?



