CountDownLatch concurrent use of tools, CyclicBarrier, Semaphore, Exchanger

1.CountDownLatch

 Allow one or more secondary synchronization thread to wait until a set of operations performed in other threads completed.

 A  CountDownLatchwith a given count initialized. awaitMethod blocks until due to the countDown()method of call which led to the current count reaches zero, after all the waiting thread is released and any subsequent await calls immediately returned. This is a one-time phenomenon - the count can not be reset. If you need to reset the version count, consider using CyclicBarrier.

public  class CountDownLatchTest { 

    public  void Meeting (a CountDownLatch CountDownLatch) { 
        System.out.println (. Thread.currentThread () getName () + "reaches the meeting room, waiting for a meeting ..." );
         the try { 
            countDownLatch.countDown (); 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } 
    } 

    public  static  void main (String [] args) { 

        // a CountDownLatch incoming number of threads, when the next execution threads executed after the completion of all the incoming, or has been wait 
        a CountDownLatch CountDownLatch = new new a CountDownLatch (. 3 );

        CountDownLatchTest countDownLatchTest = new CountDownLatchTest();
        Runnable runnable = () -> countDownLatchTest.meeting(countDownLatch);
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("全部线程执行完毕");
    }
}

 

2.CyclicBarrier

 It allows a set of threads waiting to synchronize all secondary common barrier point of each other. Loop blocking is useful in procedures involving fixed-size square of the thread, these threads must occasionally wait for each other. Barrier is called a cycle , because it can be re-used after waiting thread is released.

A CyclicBarriersupport an optional Runnablecommand, each barrier runs once, after the last thread arrives at the party, but before releasing any thread. Before any party to proceed, this barrier operation to update the shared state is useful.

public  class CyclicBarrierTest { 

    public  void Meeting (a CyclicBarrier CyclicBarrier) { 
        System.out.println (. Thread.currentThread () getName () + "reaches the meeting room, waiting for a meeting ..." );
         the try { 
            CyclicBarrier.await (); 
            the System .out.println (Thread.currentThread () getName (). + "speech ..." ); 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } 
    } 
    
    public  static  void main (String [] args) { 

        // First, the incoming number of threads CyclicBarrier construction method, the subsequent execution when the number of threads executed after the completion of all incoming otherwise have been waiting for
        CyclicBarrier = CyclicBarrier new new CyclicBarrier (3 ); 

        // CyclicBarrier constructor Second, the incoming number of threads, the number of threads when fully implemented after the completion of the incoming next execution, or else have been waiting for; the last thread execution passed after the completion of execution runnable code from the write interface to 
        a CyclicBarrier cyclicBarrier1 = new new a CyclicBarrier (. 3, () -> System.out.println (Thread.currentThread () getName () + "have all arrived, the meeting begins." )); 

        CyclicBarrierTest cyclicBarrierTest = new new CyclicBarrierTest (); 
        the Runnable Runnable = () -> cyclicBarrierTest.meeting (cyclicBarrier1);
         new new the Thread (Runnable) .start ();
         new new the Thread (Runnable) .start ();
         new new the Thread (Runnable) .start (); 
    } 
}

 

3.Semaphore

 A counting semaphore. Conceptually, a semaphore maintains a set of permits. If necessary, each acquire()will be blocked until the license is available before you can use it. Each release()add a license, potentially blocking the release of the acquirer. However, no actual permit objects; Semaphoreonly keep count of the number available, and accordingly performed

 Semaphores are typically used to limit the number of threads, rather than access to some (physical or logical) resources.

 

public class SemaphoreTest {

    public void method(Semaphore semaphore) {
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName()+" is run ...");

            Thread.sleep(2000);
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SemaphoreTest semaphoreTest = new SemaphoreTest();

        Semaphore semaphore = new Semaphore(10);

        while (true) {
            new Thread(() -> semaphoreTest.method(semaphore)).start();
        }
    }
}

 

4.Exchanger

Thread synchronization points can be exchanged and internal matching elements in the adult. Each thread in the input exchangeprovided method when some objects matching thread and collaborators, and receives the object of its partners in return. Exchange can be seen as a two-way form SynchronousQueue. Exchanger and in applications such as genetic algorithms designed piping may be useful.

public  class ExchangerTest { 
    
    public  void A (Exchanger <String> exchanger) { 
        System.out.println ( "A method to begin ..." );
         the try { 
            System.out.println ( "A data capture method begins ... " ); 
            the Thread.sleep ( 4000 ); 
            System.out.println ( " end of data capture method A " ); 

            String RES =" 12345 " ; 
            System.out.println ( " A comparative results wait " ); 
            exchanger.exchange (RES); 
        } the catch (InterruptedException E) {
            e.printStackTrace (); 
        } 
    } 

    public  void B (Exchanger <String> exchanger) { 
        System.out.println ( "Method B begin ..." );
         the try { 
            System.out.println ( "Method B begins to crawl data ... " ); 
            the Thread.sleep ( 4000 ); 
            System.out.println ( " end of data capture method B " ); 
            String RES =" 12345 " ; 
            String value = exchanger.exchange (RES); 
            the System.out .println ( "comparison results:" + value.equals (RES));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        ExchangerTest exchangerTest = new ExchangerTest();
        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(() -> exchangerTest.a(exchanger)).start();
        new Thread(() -> exchangerTest.b(exchanger)).start();
    }
}

 

Guess you like

Origin www.cnblogs.com/gyli20170901/p/10931497.html