JAVA对多线程的两个有用的辅助类(CountDownLatch和AtomicBoolean)
来源:互联网 发布:java 多态 重载 编辑:程序博客网 时间:2024/05/19 17:02
AtomicBoolean可以让一个线程等待另一个线程完成任务后再执行:
A boolean value that may be updated atomically. See the java.util.concurrent.atomic package specification for description of the properties of atomic variables. An AtomicBoolean is used in applications such as atomically updated flags, and cannot be used as a replacement for a Boolean.
public static void main(String[] args) {Thread t2 = new Thread(new BarWorker("bb"));Thread t1 = new Thread(new BarWorker("aa"));t2.run();t1.run();}private static class BarWorker implements Runnable {private static AtomicBoolean exists = new AtomicBoolean(false);private String name;public BarWorker(String name) {this.name = name;}public void run() {if (exists.compareAndSet(false, true)) { //当第一个线程设置为true后,另外的线程是进不来的System.out.println(name + " enter"+"currentvalue="+exists.get());try {System.out.println(name + " working");Thread.sleep(2000);} catch (InterruptedException e) {// do nothing}System.out.println(name + " leave");exists.set(false);} else {System.out.println(name + " give up");}}}
打印的结果:
bb entercurrentvalue=truebb workingbb leaveaa entercurrentvalue=trueaa workingaa leave
CountDownLatch
一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
如果设置 final CountDownLatch end = new CountDownLatch(10); end.countDown();可以减少计数
如果在某个地方写 end.await(); 如果计数不为0,所有线程会一直等待,计数不会被重置
private static CountDownLatch mLatch = new CountDownLatch(5);public static void main(String[] args) throws InterruptedException { final ExecutorService exec = Executors.newFixedThreadPool(10); for (int index = 0; index < 5; index++) { final int NO = index + 1; Runnable run = new Runnable() { public void run() { try { System.out.println(NO + " working"); Thread.sleep(2000); } catch (InterruptedException e) { } finally { mLatch.countDown(); } } }; exec.submit(run); } mLatch.await(); System.out.println("finish"); exec.shutdown(); }
结果:
1 working3 working2 working4 working5 workingfinish
0 0
- JAVA对多线程的两个有用的辅助类(CountDownLatch和AtomicBoolean)
- 两个重要的多线程辅助类之CyclicBarrier和CountDownLatch的用法
- 多线程辅助类-CountDownLatch的用法
- java多线程辅助类CountDownLatch
- java多线程 栅栏(CyclicBarrier) 和 多线程辅助类 CountDownLatch
- AtomicBoolean多线程的使用
- java线程同步辅助类的使用CountDownLatch
- java 多线程同步辅助类(CountDownLatch、CyclicBarrier、Semaphore、Exchanger)
- java多线程:13、CountDownLatch同步辅助类【计数器】
- Java多线程CountDownLatch的使用
- java辅助开发的两个封装类
- java CountDownLatch线程辅助类
- 多线程同步辅助类——CountDownLatch
- CountDownLatch 多线程同步辅助类用法
- 多线程辅助类之CountDownLatch(三)
- JAVA多线程—CountDownLatch-一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
- android AtomicBoolean类的使用
- Java多线程 - 浅析CountDownLatch的用法
- Flexgrid 取记录的方式
- Pentaho的印度蒙德里安Pentaho的亚太地区
- 02-4. BCD解密(10)
- HDU 3371
- Android的生命周期小结
- JAVA对多线程的两个有用的辅助类(CountDownLatch和AtomicBoolean)
- 如何使用Disruptor(一)Ringbuffer的特别
- ViewPager的双层嵌套时影响内部ViewPager的触摸滑动问题
- P1000 Galaxy Tab的概述
- QT5.3.1 + mingw4.8 调用vs2008的动态库
- 三年一小结
- Oracle解决方案和Oracle应用开发的支持延伸到开源技术
- Openpro是行业的佼佼者制造业ERP软件
- 2014上半年,免积分人气资源大集合