生活随笔
收集整理的這篇文章主要介紹了
并发辅助类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.減計數器-CountDownLatch
- 允許一個或多個線程等待直到在其他線程中執行的一組操作完成的同步輔助。
public class CountDownLatchDemo {public static void main(String
[] args
) throws InterruptedException
{CountDownLatch countDownLatch
= new CountDownLatch(20);for (int i
=1 ;i
<=20;i
++){countDownLatch
.countDown();System
.out
.println(Thread
.currentThread().getName()+">="+countDownLatch
.getCount());}System
.out
.println("我可以在Await方法之前執行");countDownLatch
.await();System
.out
.println("我為什么在最后執行呢");}
}
2.加計數器-CyclicBarrier
public class CyclicBarrierDemo {public static void main(String
[] args
) throws BrokenBarrierException
, InterruptedException
{CyclicBarrier cyclicBarrier
= new CyclicBarrier(7,()->{System
.out
.println("舍利子集齊成功,如來重生");});for (int i
=1;i
<=7;i
++){int finalI
= i
;new Thread(()->{System
.out
.println(Thread
.currentThread().getName()+":收集了"+ finalI
+"顆");try {cyclicBarrier
.await();System
.out
.println("無天必須在如來重生之后,再死");} catch (InterruptedException e
) {e
.printStackTrace();} catch (BrokenBarrierException e
) {e
.printStackTrace();}}).start();}}
}
3.Semaphore
public class SemaphoreDemo {public static void main(String
[] args
) {Semaphore semaphore
= new Semaphore(3);for (int i
=1;i
<=6;i
++){new Thread(() -> {try {semaphore
.acquire();System
.out
.println(Thread
.currentThread().getName()+"搶到了車位");TimeUnit
.SECONDS
.sleep(2);System
.out
.println(Thread
.currentThread().getName()+"離開了車位");} catch (InterruptedException e
) {e
.printStackTrace();}finally {semaphore
.release();}},String
.valueOf(i
)).start();}}}
總結
以上是生活随笔為你收集整理的并发辅助类的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。