CountDownLatch
CountDownLatch类似一个计数的工具,是等待其他线程完成工作以后,相当于加强版的join(),和join()又有所不同,join()是等待一个线程完成,而CountDownLatch只要你在进行countDown操作到0的时候,就会完成初始化,并不代表其他线程关闭了,而join()是等待其他线程执行完了才行,这一点有所不同
import java.util.concurrent.CountDownLatch;
public class countdowla {
static CountDownLatch count = new CountDownLatch(5);
public static void main(String[] args) {
Thread target = new Thread(new myThread1());
target.start();
for (int i = 0; i < 5; i++) {
new Thread(new myThread()).start();
}
}
public static class myThread implements Runnable{
@Override
public void run() {
try {
Thread.sleep(100);
System.out.println("我不牛逼");
} catch (InterruptedException e) {
e.printStackTrace();
}
count.countDown();
}
}
public static class myThread1 implements Runnable{
@Override
public void run() {
try {
count.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("牛逼");
}
}
}
结果:
我不牛逼
我不牛逼
我不牛逼
我不牛逼
我不牛逼
牛逼
CyclicBarrier
让一组线程达到某个屏障,若一组没来齐,则等待,一直到组内最后一个线程达到屏障时,屏障开放,所有被阻塞的线程会继续运行
import org.omg.PortableServer.THREAD_POLICY_ID;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class cyclictest {
static CyclicBarrier barrier = new CyclicBarrier(5,new mytask01());
public static class myTask extends Thread{
@Override
public void run() {
try {
System.out.println("is wait");
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("is run");
}
}
public static class mytask01 extends Thread{
@Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("嘿嘿嘿");
}
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new myTask().start();
}
}
}
is wait
is wait
is wait
is wait
is wait
嘿嘿嘿
is run
is run
is run
is run
is run
值得注意一点是:
CyclicBarrier构造方法可以带有一个线程对象,当屏障开放的时候,会执行这个线程
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;//线程组数
this.count = parties;//计数器
this.barrierCommand = barrierAction;//要执行的线程
}
注意一点,我一直以为屏障开放,barrierAction的执行顺序和一组线程没有先后顺序,代码测试,我错了,设置不同的sleep时间,均会先执行barrierAction。
两者的区别
CyclicBarrier更偏向于自己控制自己,CountDownLatch更侧重外部控制
CyclicBarrier操作的基本单位是线程,CountDownLatch则不是,这就意味着你可以在一个线程的run方法里面countDown多次