CountDownLatch

mac2024-05-22  33

package com.concurrent;

import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;

public class CountDownLatchTest {

         class Worker implements Runnable{                  private CountDownLatch buyLatch;

        private CountDownLatch cookLatch;                  

        public Worker(CountDownLatch buyLatch, CountDownLatch cookLatch) {             super();             this.buyLatch = buyLatch;             this.cookLatch = cookLatch;         }

 

        @Override         public void run() {             // TODO Auto-generated method stub             System.out.println("Thread " + Thread.currentThread().getName() + " is buying");             buyLatch.countDown();             try {                 TimeUnit.MILLISECONDS.sleep(100);             } catch (InterruptedException e) {                 // TODO Auto-generated catch block                 e.printStackTrace();             }             System.out.println("Thread " + Thread.currentThread().getName() + " is cooking");             cookLatch.countDown();         }              }          public static void main(String[] args){         CountDownLatch buylatch = new CountDownLatch(10);         CountDownLatch cooklatch = new CountDownLatch(10);         CountDownLatchTest test = new CountDownLatchTest();         for(int i = 0 ; i < 10; i++){             new Thread(test.new Worker(buylatch, cooklatch)).start();         }         try {             buylatch.await();         } catch (InterruptedException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }         System.out.println("Buying is done");         try {             cooklatch.await();         } catch (InterruptedException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }         System.out.println("Cooking is done");     }      }

Note:

When using a CyclicBarrier, the assumption is that you specify the number of waiting threads that trigger the barrier. If you specify 5, you must have at least 5 threads to call await().

When using a CountDownLatch, you specify the number of calls to countDown() that will result in all waiting threads being released. This means that you can use a CountDownLatch with only a single thread.

 

最新回复(0)