三个线程轮流执行顺序打印10次ABC,依次是ABCABCABC
今天遇到的一道笔试题,为保证线程线程顺序执行,每次执行分别给A,B,C线程休眠1,2,3毫秒,然后调用CyclicBarrier的await方法即可。
package test;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Tester {
private final static ExecutorService executor=Executors.newCachedThreadPool();
private CyclicBarrier cyclicBarrier=new CyclicBarrier(3);
private class Handler implements Runnable{
private String name;
private int time;
public Handler(String name,int time) {
this.name=name;
this.time=time;
}
public void run() {
try {
for(int i=0;i<10;i++) {
Thread.sleep(time);
System.out.print(name);
cyclicBarrier.await();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
public void start() {
executor.execute(new Handler("A", 1));
executor.execute(new Handler("B", 2));
executor.execute(new Handler("C", 3));
executor.shutdown();
}
public static void main(String[] args) {
new Tester().start();
}
}