JDK5 new features thread Synchronization tool Class (III)

Source: Internet
Author: User
Tags semaphore

I. Semaphore

Semaphore can control the number of threads that access resources at the same time, such as the number of concurrent visits that implement a file consent.

semaphore implementation of the function is similar to the toilet all 5 pits, the increase of 10 people to go to the toilet, then only 5 people can occupy at the same time, when no one of the 5 men left, one of the other 5 people waiting was able to occupy it. The other 5 people who are waiting can be given a chance at random, and will be able to get an opportunity in the order of first served, depending on the parameters passed in when constructing the semaphore object.

public class Semaphoretest {public static void main (string[] args) {//Create a thread pool executorservice service = Executors.newcache Dthreadpool (); final Semaphore sp = new Semaphore (3); Indicates that there are currently 3 lights (consent 3 concurrent)//start 5 threads for (int i = 0; i < 5; i++) {Service.execute (new Runnable () {public void run () {try {Sp.acq Uire (); Light a lamp//availablepermits: Indicates the light System.out.println ("thread" + thread.currentthread ()) that can be used. GetName () + "Enter, current" + (3-sp.ava Ilablepermits ()) + "concurrency"); Thread.Sleep ((Long) (Math.random () * 10000)); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "about to leave"); Sp.release (); Turn off a lamp (release) System.out.println ("Thread" + thread.currentthread (). GetName () + "left, current" + (3-sp.availablepermits ()) + "concurrency" );} catch (Interruptedexception e) {e.printstacktrace ();}}});}}}
a single Semaphore object can implement mutually exclusive locks, and it can be a thread that obtains a "lock", and then a thread releases "lock", which can be applied to some occasions of deadlock recovery.

Thread Pool-1-thread-1 entered, there are currently 1 concurrent threads Pool-1-thread-2 entered, there are currently 2 concurrent threads Pool-1-thread-4 entered, there are currently 3 concurrent threads pool-1-thread-4 The outgoing thread pool-1-thread-4 is leaving. There are currently 2 concurrent threads Pool-1-thread-3 entered. There are currently 3 concurrent threads pool-1-thread-2 leaving the thread pool-1-thread-2 has left, and there are currently 2 concurrent threads Pool-1-thread-5 entered. There are currently 3 concurrent threads pool-1-thread-5 leaving the thread pool-1-thread-5 has left, there are currently 2 concurrent threads pool-1-thread-1 is about to leave the thread pool-1-thread-1 has left, There are currently 1 concurrent threads pool-1-thread-3 leaving the thread pool-1-thread-3 has left, and there are currently 0 concurrent


Two. Cyclicbarrier

It means we wait for each other. Set up before starting to start, scattered activities and meet at the designated place.

It's like taking a weekend-time group outing across the company. The first departure from home to the company collection, and then the same time to go to the park to play, in the designated place after the same time to start eating.

public class Cyclicbarriertest {public static void main (string[] args) {//Open a thread pool executorservice executorservice = execut Ors.newcachedthreadpool ();//Number 3: Indicates that there are 3 of them to go down. Otherwise, it waits for the final cyclicbarrier cb = new Cyclicbarrier (3);//create 3 threads for (int i = 0; i < 3; i++) {Executorservice.execute (NE W Runnable () {@Overridepublic void run () {try {Thread.Sleep ((long) (Math.random () * 1000))//per thread "rest" time is different SYSTEM.OUT.P RINTLN ("Thread" + thread.currentthread (). GetName () + "Arrival meeting place 1. There is currently "+ (cb.getnumberwaiting () + 1) +" One has arrived, "+ (cb.getnumberwaiting () = = 2?                       "All is up, move on": "Waiting"); Cb.await (); The first-come-wait-after-arrival will continue to run down Thread.Sleep ((Long) (Math.random () * 1000) when all 3 arrive. Each thread "rests" at a different time System.out.println ("thread" + thread.currentthread (). GetName () + "coming to the rendezvous point 2. There is currently "+ (cb.getnumberwaiting () + 1) +" One has arrived, "+ (cb.getnumberwaiting () = = 2? "It's all here." Go forward ":" Waiting "); cb.await (); Thread.Sleep ((Long) (Math.random () *1000)); Each thread "rests" the time differently System.out.println ("thread" + Thread.currenttHread (). GetName () + "arriving at meeting point 3, currently has" + (cb.getnumberwaiting () + 1) + "one has arrived. "+ (cb.getnumberwaiting () = = 2?" It's all here.                     Go forward ":" Waiting "));                     Cb.await ();               } catch (Exception e) {e.printstacktrace ();} }});} Executorservice.shutdown ();}}
Three threads finish their respective tasks, and at different times they arrive at the rendezvous point, and then they are able to go on with their work, then arrive at the new rendezvous, and then go to their work.

Thread pool-1-thread-2 is about to arrive at meeting Place 1, currently 1 have arrived, waiting for thread pool-1-thread-3 to arrive at meeting point 1, currently 2 have arrived, waiting for thread pool-1-thread-1 to arrive at meeting point 1 , there are currently 3 already arrived. All the way, move on. Thread pool-1-thread-2 is about to arrive at meeting point 2. There are currently 1 already arrived. Waiting for thread pool-1-thread-3 to arrive at meeting point 2, currently 2 have arrived. Waiting for thread pool-1-thread-1 to arrive at meeting point 2. There are currently 3 already arrived. It's all here. Continue to advance thread pool-1-thread-3 is about to arrive at meeting point 3, currently 1 have arrived. Waiting for thread pool-1-thread-2 to arrive at meeting point 3, currently 2 have arrived, waiting for thread pool-1-thread-1 to arrive at meeting point 3, currently 3 have arrived, all to the same, continue to move forward

Three. Countdownlatch

Like a countdown counter, the countdown method that calls the Countdownlatch object is reduced by one, and when the count arrives 0 o'clock, all the waiting or a single waiting person starts to run.

Application: A referee's password, the athlete starts running at the same time, when all the athletes run to the end of the referee published results. It is also possible to achieve a plan that requires the ability of multiple leaders to continue to implement their competencies after signing.

public class Countdownlatchtest {public static void main (string[] args) throws Exception {Executorserv                    Ice Service = Executors.newcachedthreadpool ();                   Child counter, Count is 1 final countdownlatch subcounter = new Countdownlatch (1);           Main counter, Count is 3 final countdownlatch maincounter = new Countdownlatch (3); for (int i = 0; i < 3; i++) {Service.execute (new Runnable () {@Override P ublic void Run () {try {System.out.println ("thread" + thread.currentthread (). GE Tname () + "is ready to accept the command.                                                     "); Subcounter.await (); The child thread waits for System.out.println ("thread" + thread.currentthread (). GetName () + "accepted Make!                          ");                          Thread.Sleep ((Long) math.random () * 10000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "Response life"Make the processing result! 

"); Maincounter.countdown (); Reduce the counter body count by 1, and when the count is 0 o'clock, the main thread will start running} catch (Exception e) { E.printstacktrace (); } } } ); } thread.sleep ((Long) math.random () * 1000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "Upcoming orders!" "); Subcounter.countdown (); Subtract 1 from the count on the counter, and when the count is 0 o'clock, the child thread starts to run SYSTEM.OUT.PRINTLN ("thread" + thread.currentthread (). GetName () + "sent command, waiting for results." "); Maincounter.await (); The main thread waits for System.out.println ("thread" + thread.currentthread (). GetName () + "received all response results!

"); Service.shutdown (); } }

Thread pool-1-thread-1 is preparing to accept commands. Thread pool-1-thread-3 is ready to accept commands! Thread pool-1-thread-2 is ready to accept commands!

Thread main is about to announce the command!

The thread main has sent the command. Waiting for results!

Thread Pool-1-thread-2 has accepted the command! Thread Pool-1-thread-3 has accepted the command. Thread Pool-1-thread-1 has accepted the command. Thread pool-1-thread-3 responds to command processing results! Thread pool-1-thread-2 responds to command processing results! The thread pool-1-thread-1 responds to the command processing result. Thread main has received all response results!


Four. Exchanger

Used to achieve data exchange between two people, each person after the completion of a certain transaction to exchange data with each other, the first person to take out the data will be waiting for the second person to hold the data to come, the ability to exchange data with each other:

public class Exchangertest {public static void main (string[] args) {Executorservice Service = Executors.newcachedthreadpool (); final Exchanger Exchanger = new Exchanger (); Service.execute (new Runnable () {@ overridepublic void Run () {try {String data1 = "AAA"; SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "getting data:" + data1 + "swap out! "); Thread.Sleep ((Long) math.random () * 10000); String data2 = (string) exchanger.exchange (data1); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "The data returned is:" + data2);} catch (Exception e) {}}}); Service.execute (new Runnable () {@Overridepublic void run () {try {String data1 = "BBB"; SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "getting data:" + data1 + "swap out! "); Thread.Sleep ((Long) math.random () * 10000); String data2 = (string) exchanger.exchange (data1); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "The data returned is:" + data2);} catch (Exception e) {}}});}} 
Thread pool-1-thread-1 is putting the data: AAA swap out!

Thread pool-1-thread-2 is putting the data: BBB in exchange! The data returned by the thread pool-1-thread-1 is: The BBB thread pool-1-thread-2 the data returned as: AAA





JDK5 new features thread Synchronization tool Class (III)

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.