您的位置:首页 > 其它

多线程合作顺序执行

2018-01-31 10:40 218 查看

第一种方法

用Java.util.concurrent下的方法解决

用CountDownLatch : 一个线程(或者多个), 等待另外N个线程完成某个事情之后才能执行

CountDownLatch 是计数器, 线程完成一个就记一个, 就像 报数一样, 只不过是递减的.

public class CountDownLatchDemo {
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();
}
}
}

}


第二种方法

直接用join把线程5加入进去即可

public static void main(String[] args) throws InterruptedException
{
Thread t1 = new Thread(new Worker("thread-1"));
Thread t2 = new Thread(new Worker("thread-2"));
Thread t3 = new Thread(new Worker("thread-3"));
Thread t4 = new Thread(new Worker("thread-4"));
Thread t5 = new Thread(new Worker("thread-5"));

t1.start();t2.start();t3.start();t4.start();
t1.join();t2.join();t3.join();t4.join();

t5.start();
t5.join();
}


第三种方法

/**
* 假如有Thread1、Thread2、ThreaD3、Thread4四条线程分别统计C、D、E、F四个盘的大小,所有线程都统计完毕交给Thread5线程去做汇总,应当如何实现?
*/
public class TestThread {
public static void main(String[] args) {
ThreadCount tc = null;
ExecutorService es = Executors.newCachedThreadPool();//线程池
CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(es);
for(int i=0;i<4;i++){
tc = new ThreadCount(i+1);
cs.submit(tc);
}

// 添加结束,及时shutdown,不然主线程不会结束
es.shutdown();

int total = 0;
for(int i=0;i<4;i++){
try {
total+=cs.take().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

System.out.println(total);
}
}

class ThreadCount implements Callable<Integer>{
private int type;
ThreadCount(int type){
this.type = type;
}
@Override
public Integer call() throws Exception {
if(type==1){
System.out.println("C盘统计大小");
return 1;
}else if(type==2){
Thread.sleep(20000);
System.out.println("D盘统计大小");
return 2;
}else if(type==3){
System.out.println("E盘统计大小");
return 3;
}else if(type==4){
System.out.println("F盘统计大小");
return 4;
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: