Java_ Concurrent Threads _semaphore, Countdownlatch, Cyclicbarrier, Exchanger

Source: Internet
Author: User

1.Semaphore

The semaphore (Semaphore), sometimes called a semaphore, is a facility used in a multithreaded environment that coordinates individual threads to ensure that they are able to use public resources correctly and rationally.
Semaphore is currently used in multi-threaded environments, the operating system semaphore is a very important concept, in the process of control has been applied. Java Concurrency Library semaphore can easily complete semaphore control, Semaphore can control the number of simultaneous accesses to a resource, obtain a license through acquire (), and release () releases a license if it is not waiting. For example, under Windows, you can set the maximum number of client accesses for a shared file.
Semaphore implementation of the function is similar to the toilet has 5 pits, if there are 10 people to the toilet, then at the same time only how many people to go to the toilet? At the same time only 5 people can occupy, when any one of the 5 people out of the way, one of the other 5 waiting for a person to occupy. The other 5 people who are waiting can be given a chance at random, or they can be given an opportunity in the order of first served, depending on the parameter options passed in when constructing the semaphore object. The semaphore object of a single semaphore can implement a mutex function, and it can be a thread that obtains a "lock", and another thread releases the "lock", which can be applied to some occasions of deadlock recovery.

public static void Main (string[] args) {//thread pool Executorservice exec = Executors.newcachedthreadpool ();//only 5 threads simultaneously access final S Emaphore semp = new Semaphore (5);//Simulate 20 client access for (int index = 0; index <; index++) {final int NO = index; Runnable run = new Runnable () {public void run () {try {//Get license Semp.acquire (); Try{system.out.println ("Accessing:" + NO); Thread.Sleep ((Long) (Math.random () * 10000)); After finally{//access, release, if the following statement is masked, the console can only print 5 records, then the thread has been blocked semp.release ();}} catch (Interruptedexception e) {}}};exec.execute (run);} Exit thread pool Exec.shutdown ();}

2.CountDownLatch

The Countdownlatch class is a synchronous counter that, when constructed, receives an initial value by default, and each time the countdown () method is called, the counter is reduced by 1. When the counter >0, the await () method blocks, and when the counter =0, it receives an await () response immediately.


3.CyclicBarrier

Cyclicbarrier a synchronization helper class that allows a set of threads to wait for each other until a common barrier point (common barrier points) is reached. Applies when all subtasks are completed before the Executive Director.

public class Main {public static void main (string[] args) {//If the parameter is changed to 4, but only 3 players are added below, this waits forever//Waits until all parties has Invoked await on the this barrier. Cyclicbarrier barrier = new Cyclicbarrier (3); Executorservice executor = Executors.newfixedthreadpool (3); Executor.submit (new Thread (New Runner (barrier, "1th player")); Executor.submit (new Runner (barrier, "number 2nd")), Executor.submit (new Thread (Runner, "3rd")); Executor.shutdown ();}} Class Runner implements Runnable {///A synchronization helper class that allows a set of threads to wait for each other until a public barrier (common barrier point) is reached private cyclicbarrier barrier ;p rivate String name;public Runner (cyclicbarrier barrier, String name) {super (); this.barrier = Barrier;this.name = name;} @Overridepublic void Run () {try {thread.sleep (New Random ()). Nextint (8)); SYSTEM.OUT.PRINTLN (name + "Ready ...");//The await method of barrier will wait until all participants have already raised the await method in this barrier. Barrier.await ();} catch (Interruptedexception e) {e.printstacktrace ();} catch (Brokenbarrierexception e) {e.printstacktrace ();} SystEM.OUT.PRINTLN (name + "Starting!") ");}} /* * # 2nd is ready ... Player number 1th is ready ... Player number 3rd is ready ... Contestant Number 3rd starts! Contestant Number 2nd starts! Contestant number 1th starts! */

4.Exchanger

Exchanger can exchange data between two threads, only 2 threads, and he does not support the interchange of data between more than one thread. When thread A calls the Exchange () method of an Exchange object, he falls into a blocking state until thread B also calls the Exchange () method, and then swaps the data in a thread-safe fashion after threads A and b continue to run.

public class Threadlocaltest {public static void main (string[] args) {exchanger<list<integer>> Exchanger = NE W exchanger<> (); new Consumer (Exchanger). Start (); new Producer (Exchanger). Start ();} Class Producer extends Thread {list<integer> List = new arraylist<> (); exchanger<list<integer>> Exchanger = Null;public Producer (exchanger<list<integer>> EXCHANGER) {super (); this.exchanger = exchanger;} @Overridepublic void Run () {Random rand = new Random (), for (int i=0; i<10; i++) {list.clear (); List.add (Rand.nextint (100 List.add (Rand.nextint (10000)); List.add (Rand.nextint (10000)); List.add (Rand.nextint (10000)); List.add ( Rand.nextint (10000)); try {list = Exchanger.exchange (list);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} Class Consumer extends Thread {list<integer> List = new arraylist<> (); exchanger<list<integer>> Exchanger = Null;public Consumer (exchanger<list<integer>> Exchanger) {super (); this.exchanger = exchanger;}  @Overridepublic void Run () {for (int i=0; i<10; i++) {try {list = Exchanger.exchange (list);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.print (list.get (0) + ","); System.out.print (List.get (1) + ","); System.out.print (List.get (2) + ","); System.out.print (List.get (3) + ","); System.out.println (List.get (4) + ",");}}}

Java_ Concurrent Threads _semaphore, Countdownlatch, Cyclicbarrier, Exchanger

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.