CountDownLatch的作用,某一个线程等待所有其他的线程执行完毕或者执行到某一步。
使用示例:
public class VolatileTest {
private volatile int i = 0;
private void increate(){
i++;
}
public static void main(String[] args){
//创建CountDownLatch对象
CountDownLatch countDownLatch = new CountDownLatch(10);
VolatileTest t = new VolatileTest();
for(int k=0;k<10;k++){
new Thread(){
public void run(){
for(int n=0;n<1000;n++) {
t.increate();
}
System.out.println("over!");
//执行完毕,调用此方法
countDownLatch.countDown();
}
}.start();
}
try {
//等待10个线程执行完毕
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.i);
}
}
CyclicBarrier的作用与CountDownLatch相反:是所有线程都等待大家都处在某一个状态(某一步),然后才能往下执行。
该对象可重复使用,可设置等待超时时间。
使用示例:
public class CyclicBarrierTest implements Runnable{
CyclicBarrier cb = null;
String threadName = null;
public CyclicBarrierTest(CyclicBarrier cb,String name){
this.cb = cb;
this.threadName = name;
}
@Override
public void run() {
try {
Thread.sleep((int)Math.floor(Math.random()*2000)); //设置一个随机等待的时间,让效果明显
System.out.println(String.format("%s is working now! ",threadName));
//等待所有的线程
cb.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(String.format("All is Ok! ,%s is working again!",threadName));
}
public static void main(String[] args){
//构造方法
CyclicBarrier cb =new CyclicBarrier(3);
for (int i=0;i<3;i++){
CyclicBarrierTest t = new CyclicBarrierTest(cb,"thread-"+i);
new Thread(t).start();
}
}
}
Semaphore,信号量,类似于锁,只有线程获取到了许可,才可以执行。
方法:acquire()获取许可,没有获取到则等待;
release()释放许可;
boolean tryAcquire()尝试获得许可,没有获取到则立即返回false,获取到则返回true;
示例:
public class SemaphoreTest extends Thread {
Semaphore semaphore = null;
String name = null;
public SemaphoreTest(Semaphore semph, String name) {
this.semaphore = semph;
this.name = name;
}
public void run() {
try {
semaphore.acquire();
System.out.println(String.format(" %s get a semaphore, now I am doing work!", name));
Thread.sleep(3000);
System.out.println(String.format(" %s have finished work!", name));
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
Semaphore semaphore = new Semaphore(3);
for(int i=0;i<10;i++){
SemaphoreTest t = new SemaphoreTest(semaphore,"thread-"+i);
t.start();
}
}
}