日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java boolean 多线程_JAVA多线程两个实用的辅助类(CountDownLatch和AtomicBoolean)

發布時間:2024/7/23 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java boolean 多线程_JAVA多线程两个实用的辅助类(CountDownLatch和AtomicBoolean) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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=true

bb working

bb leave

aa entercurrentvalue=true

aa working

aa 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 working

3 working

2 working

4 working

5 working

finish

版權聲明:本文博客原創文章,博客,未經同意,不得轉載。

總結

以上是生活随笔為你收集整理的java boolean 多线程_JAVA多线程两个实用的辅助类(CountDownLatch和AtomicBoolean)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。