Java中的門閂和柵欄是一種同步工具,用于管理多線程程序中的并發問題。
門閂是一種阻塞對象,它允許線程一直等待,直到其他線程完成某些操作后才能繼續執行。在Java中,門閂可以使用CountDownLatch類來實現。
public class CountDownLatchExample { public static void main(String[] args) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(3); new Thread(new Runnable() { public void run() { System.out.println("Thread1 is executing"); latch.countDown(); } }).start(); new Thread(new Runnable() { public void run() { System.out.println("Thread2 is executing"); latch.countDown(); } }).start(); new Thread(new Runnable() { public void run() { System.out.println("Thread3 is executing"); latch.countDown(); } }).start(); latch.await(); System.out.println("All threads have finished executing"); } }
在上面的代碼中,我們創建了一個CountDownLatch實例,并將其初始化為3。然后我們啟動了三個線程,并在每個線程的run()方法中調用了countDown()方法。最后,我們調用await()方法來等待所有線程執行完成,這樣才能輸出"All threads have finished executing"。
柵欄是一種同步點,它允許一組線程在一個確定的點上等待彼此,并且只有當所有線程都到達這個點時才能繼續執行。在Java中,柵欄可以使用CyclicBarrier類來實現。
public class CyclicBarrierExample { public static void main(String[] args) throws InterruptedException, BrokenBarrierException { final CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() { public void run() { System.out.println("All threads have reached the barrier, starting..."); } }); new Thread(new Runnable() { public void run() { try { System.out.println("Thread1 is waiting at the barrier"); barrier.await(); System.out.println("Thread1 has started running"); } catch(Exception e) {} } }).start(); new Thread(new Runnable() { public void run() { try { System.out.println("Thread2 is waiting at the barrier"); barrier.await(); System.out.println("Thread2 has started running"); } catch(Exception e) {} } }).start(); new Thread(new Runnable() { public void run() { try { System.out.println("Thread3 is waiting at the barrier"); barrier.await(); System.out.println("Thread3 has started running"); } catch(Exception e) {} } }).start(); Thread.sleep(5000); new Thread(new Runnable() { public void run() { try { System.out.println("Thread4 is waiting at the barrier"); barrier.await(); System.out.println("Thread4 has started running"); } catch(Exception e) {} } }).start(); } }
在上面的代碼中,我們創建了一個CyclicBarrier實例,并將其初始化為3。我們啟動了三個線程,并在每個線程的run()方法中調用了await()方法。由于柵欄的容量為3,所以線程1到線程3必須都到達柵欄之后才能繼續執行。最后,我們啟動了第四個線程,并在等待5秒后再次調用await()方法。
上一篇java隊列和棧 共同
下一篇css支持點劃線嗎