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)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【LeetCode笔记】617. 合并二
- 下一篇: java jni helloword_J