62,614
社区成员
发帖
与我相关
我的任务
分享
package test.thread.newfunction;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CyclicBarrierTest3 {
public CyclicBarrierTest3(){
CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() {
@Override
public void run() {
System.out.println("所有线程都执行完了!");
}
});
ExecutorService exec = Executors.newFixedThreadPool(2);
Task t1 = new Task(barrier, 1, 3000);
Task t2 = new Task(barrier, 2, 1000);
exec.submit(t1);
exec.submit(t2);
exec.shutdown();
}
static String now() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date()) + ": ";
}
static class Task implements Runnable {
private int threadNo = -1;
private int time = 0;
private CyclicBarrier barrier;
public Task(CyclicBarrier barrier, int threadNo, int time) {
this.barrier = barrier;
this.threadNo = threadNo;
this.time = time;
}
public void run() {
try {
System.out.println(now() + "第" + threadNo + "号线程在执行");
Thread.sleep(time);
System.out.println(now() + "第" + threadNo + "号线程执行完毕!!! 花费" + (time/1000) + "秒");
barrier.await();
} catch (InterruptedException e) {
} catch (BrokenBarrierException e) {
}
}
}
public static void main(String[] args) {
new CyclicBarrierTest3();
}
}
public CyclicBarrierTest3() {
CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {
@Override
public void run() {
System.out.println("所有线程都执行完了!");
}
});
ExecutorService exec = Executors.newFixedThreadPool(2);
for(int i=0;i<10;i++){//循环10次试试
barrier.reset();
Task t1 = new Task(barrier, 1, 3000);
Task t2 = new Task(barrier, 2, 1000);
exec.submit(t1);
exec.submit(t2);
try {
barrier.await();
System.out.println(now() + "一次循环已经搞定啦。");
} catch (InterruptedException e) {
} catch (BrokenBarrierException e) {
}
}
exec.shutdown();
}
while(true){
ExecutorService exec = Executors.newFixedThreadPool(2);
Task t1 = new Task(barrier, 1, 3000);
Task t2 = new Task(barrier, 2, 1000);
exec.submit(t1);
exec.submit(t2);
exec.shutdown();
while(true){
if(exec.isTerminated()){ break;} else(Thread.sleep(100);)
}
}