Multithreading-countdownlatch,cyclicbarrier,semaphore,exchanger,phaser

Source: Internet
Author: User
Tags semaphore

Countdownlatch
A synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed. Initializes the countdownlatch with the given count. Call the countdown () count minus one, and the await () method will block until the count reaches 0, and the count cannot be reset.

public class Countdownlatch {    private final sync sync;    public Countdownlatch (int count);    public void Countdown () {        sync.releaseshared (1);    }    public void await () throws Interruptedexception {        sync.acquiresharedinterruptibly (1);    }    Public boolean await (long timeout, timeunit unit) throws Interruptedexception {        return Sync.tryacquiresharednanos ( 1, Unit.tonanos (timeout));}    }

There are mainly countdown () and await () methods in the

Countdownlatch.  
Countdown () decrements the count, if the count reaches 0, whether all waiting threads.  
1. If the current count is greater than 0, the count is reduced by one;  
2. If the count is zero after minus one, all threads waiting for the count to be zero are re-dispatched,  
3. If the count is zero, no action is taken;  
Await () causes the current thread to block until the count is zero, unless the thread is interrupted or exceeds the specified wait time,  
If the count is zero, returns TRUE&NBSP immediately;
When entering this method, the current thread has set the interrupt state or is interrupted while waiting. Throws a interruptedexception exception and clears the interrupt state of the current thread. If the specified wait time is exceeded, false is returned, and if the time is less than or equal to zero, this method does not wait at all.

Package Org.github.lujiango;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.TimeUnit; public class Test16 {public static void main (string[] args) throws Interruptedexception {final Countdownlatch        begin = New Countdownlatch (1);        Final Countdownlatch end = new Countdownlatch (10);        Final Executorservice exec = Executors.newfixedthreadpool (10);            for (int i = 0; i < i++) {final int no = i + 1;                        Runnable run = new Runnable () {@Override public void run () {try {                        Begin.await ();                        TimeUnit.MILLISECONDS.sleep ((Long) (Math.random () * 10000));                    System.out.println ("No." + No + "arrived");                    } catch (Exception e) {} finally {End.countdown ();   }             }            };        Exec.submit (run);        } System.out.println ("Game start");        Begin.countdown ();        End.await ();        System.out.println ("Game over");    Exec.shutdown (); }}

cyclicbarrier  
A synchronization helper class that allows a set of threads to wait until a common barrier point is reached. In programs that involve a set of fixed-size threads, these threads must wait for each other at a time.

Package Org.github.lujiango;import Java.util.concurrent.brokenbarrierexception;import Java.util.concurrent.cyclicbarrier;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.timeunit;public class Test16 {public static void main (Stri        Ng[] args) throws Interruptedexception, brokenbarrierexception {final cyclicbarrier end = new Cyclicbarrier (10);        Final Executorservice exec = Executors.newfixedthreadpool (10);        System.out.println ("Game start");            for (int i = 0; i < i++) {final int no = i + 1;                        Runnable run = new Runnable () {@Override public void run () {try {                        End.await ();                        TimeUnit.MILLISECONDS.sleep ((Long) (Math.random () * 10000));                    System.out.println ("No." + No + "arrived");            } catch (Exception e) {} finally {        }                }            };        Exec.submit (run);        } System.out.println ("Game over");    Exec.shutdown (); }}

When all subtasks are required to complete, the main task is performed, and this time you can choose to use Cyclicbarrier.

Semaphore
A count semaphore, the semaphore maintains a license set that blocks each acquire () before the license is available, and then obtains the license. Each release () releases the license, which may release a blocking fetch.
The semaphore only counts the number of available licenses and takes action, and the thread that gets the signal can enter the code or wait.

Package Org.github.lujiango;import Java.util.concurrent.executorservice;import java.util.concurrent.Executors; Import Java.util.concurrent.semaphore;import Java.util.concurrent.timeunit;public class Test17 {public static void Mai        N (string[] args) {Executorservice exec = Executors.newcachedthreadpool ();        Final Semaphore semp = new Semaphore (5);            for (int i = 0; i <; i++) {final int no = i;                        Runnable run = new Runnable () {@Override public void run () {try {                        Semp.acquire ();                        System.out.println ("Accessing:" + No);                    TimeUnit.MILLISECONDS.sleep ((Long) (Math.random () * 10000));                    } catch (Exception e) {} finally {semp.release ();            }                }            };        Exec.submit (run);    } exec.shutdown (); }}

Exchanger  
Exchanger can exchange data between two threads, only two threads, and does not support the interchange of data between more than one thread. &NBSP
When thread A calls the Exchanger object's Exchage () method, it blocks until the B thread also calls the Exchange () method, and the thread then exchanges the data in a secure manner, after which A and B threads continue to execute.

Package Org.github.lujiango;import Java.util.arraylist;import Java.util.list;import java.util.random;import Java.util.concurrent.exchanger;public class Test18 {public static void main (string[] args) {exchanger<list&        lt;integer>> ex = new Exchanger<list<integer>> ();        New A (ex). Start ();    New B (ex). Start ();    }}class A extends Thread {list<integer> List = new arraylist<integer> ();    Exchanger<list<integer>> ex;    Public A (Exchanger<list<integer>> ex) {this.ex = ex;        } @Override public void Run () {Random random = new random ();            for (int i = 0; i < i++) {list.clear ();            List.add (Random.nextint (10));            List.add (Random.nextint (10));            List.add (Random.nextint (10));            try {list = Ex.exchange (list); } catch (Exception e) {}}}}class B extends Thread {list<integer> list = new arraylist<integer> ();    Exchanger<list<integer>> ex;    Public B (Exchanger<list<integer>> ex) {this.ex = ex; } @Override public void Run () {for (int i = 0; i < i++) {try {list = EX.E            Xchange (list);        } catch (Exception e) {} System.out.println (list); }    }}

Phaser  
Phaser is a flexible thread synchronization tool that contains Countdownlatch and Cyclicbarrier related features.  
Countdownlatch's Countdown () and await () can be replaced arrive by Phaser awaitadvance () and   (int n);
The cyclicbarrier await can use the Phaser arriveandawaitadvance () method instead of the  
Phaser instead of Countdownlatch:

package Org.github.lujiango;import Java.util.concurrent.phaser;import Java.util.concurrent.timeunit;public class Test19 {public static void main (string[] args) throws Interruptedexception        {Final Phaser latch = new Phaser (10);            for (int i = 1; i <=; i++) {final int id = i; Thread t = new Thread (new Runnable () {@Override public void run () {try                        {TimeUnit.SECONDS.sleep ((long) (Math.random () * 10));                    System.out.println ("Thread:" + ID + "is running");                    } catch (Interruptedexception e) {e.printstacktrace ();                    } finally {latch.arrive ();            }                }            });        T.start ();        } latch.awaitadvance (Latch.getphase ());    SYSTEM.OUT.PRINTLN ("All thread has run"); }}
package Org.github.lujiango;import Java.util.concurrent.phaser;import Java.util.concurrent.timeunit;public class Test19 {public static void main (string[] args) throws Interruptedexception        {Final Phaser latch = new Phaser (10);            for (int i = 1; i <=; i++) {final int id = i; Thread t = new Thread (new Runnable () {@Override public void run () {try                        {TimeUnit.SECONDS.sleep ((long) (Math.random () * 10)); Latch.arriveandawaitadvance ();                    All threads are executed here before execution continues, otherwise all blocks System.out.println ("thread:" + ID + "is running");                    } catch (Interruptedexception e) {e.printstacktrace ();                    } finally {latch.arrive ();            }                }            });        T.start (); }    }}

  

Multithreading-countdownlatch,cyclicbarrier,semaphore,exchanger,phaser

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.