线程同步辅助-CyclicBarrier指的是属于同一个线程组中的线程必须在指定的集合点上到齐。其中最重要的方法就是await方法。
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestCyclicBarrier {
public static void main(String[] args){
//创建需要同步三个线程的同步辅助对象
CyclicBarrier barrier=new CyclicBarrier(3);
//创建容量为三的固定线程池
ExecutorService exec=Executors.newFixedThreadPool(3);
//向线程池中提交三个任务
exec.submit(new Runner(barrier,0,new int[]{4,8,18}));
exec.submit(new Runner(barrier,1,new int[]{1,2,3}));
exec.submit(new Runner(barrier,2,new int[]{4,5,8}));
exec.shutdown();
}
}
import java.util.Date;
import java.util.concurrent.CyclicBarrier;
public class Runner implements Runnable{
private int no=0;//线程序号
private int[] times=null;//到达每个集合点需要的时间,单位为秒
private CyclicBarrier barrier=null;//同步辅助对象
public Runner(CyclicBarrier barroer,int no, int[] times){
this.no=no;
this.barrier=barroer;
this.times=times;
}
public void run() {
try{
Thread.sleep(times[0]*1000);
System.out.println(new Date()+" thread_"+no);
barrier.await();
Thread.sleep(times[1]*1000);
System.out.println(new Date()+" thread_"+no);
barrier.await();
Thread.sleep(times[2]*1000);
System.out.println(new Date()+" thread_"+no);
barrier.await();
}catch (Exception e) {
// TODO: handle exception
}
}
}
线程池的容量不能小于任务数。。。
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestCyclicBarrier {
public static void main(String[] args){
//创建需要同步三个线程的同步辅助对象
CyclicBarrier barrier=new CyclicBarrier(3);
//创建容量为三的固定线程池
ExecutorService exec=Executors.newFixedThreadPool(3);
//向线程池中提交三个任务
exec.submit(new Runner(barrier,0,new int[]{4,8,18}));
exec.submit(new Runner(barrier,1,new int[]{1,2,3}));
exec.submit(new Runner(barrier,2,new int[]{4,5,8}));
exec.shutdown();
}
}
import java.util.Date;
import java.util.concurrent.CyclicBarrier;
public class Runner implements Runnable{
private int no=0;//线程序号
private int[] times=null;//到达每个集合点需要的时间,单位为秒
private CyclicBarrier barrier=null;//同步辅助对象
public Runner(CyclicBarrier barroer,int no, int[] times){
this.no=no;
this.barrier=barroer;
this.times=times;
}
public void run() {
try{
Thread.sleep(times[0]*1000);
System.out.println(new Date()+" thread_"+no);
barrier.await();
Thread.sleep(times[1]*1000);
System.out.println(new Date()+" thread_"+no);
barrier.await();
Thread.sleep(times[2]*1000);
System.out.println(new Date()+" thread_"+no);
barrier.await();
}catch (Exception e) {
// TODO: handle exception
}
}
}
线程池的容量不能小于任务数。。。