Thread advanced application-6-JAVA5 thread Concurrent Library Synchronization tool Class (Synchronizers), new knowledge for large use

Source: Internet
Author: User
Tags mutex semaphore

1. Popularization of new knowledge

2. The use case of Semaphore tool class package com.java5.thread.newSkill;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.Semaphore; The use case of/** * Semaphore Tool class * is somewhat similar to the mutex lock, except that only one mutex is available, and the semaphore can have multiple * semaphore: Semaphore/public class Semaphoretest {public Stati
		c void Main (string[] args) {Executorservice service = Executors.newcachedthreadpool ();
		Final semaphore sp = new semaphore (3);
						for (int i=0;i<10;i++) {Runnable Runnable = new Runnable () {@Override the public void run () {try {
					Acquire: obtain; The following method is to obtain the signal light sp.acquire ();
					catch (Interruptedexception e) {e.printstacktrace (); //availablepermits (): The License System.out.println ("Thread" +thread.currentthread () is available. GetName () + "Enter, currently existing" + (3-sp.avail Ablepermits ()) + "concurrency."
					
					");
					try {thread.sleep (long) math.random () *10000);
					catch (Interruptedexception e) {e.printstacktrace (); } System.out.println ("Thread"+thread.currentthread (). GetName () + "is about to leave."
					");
					Release signal light sp.release (); The following code sometimes performs inaccurate System.out.println ("thread" +thread.currentthread (). GetName () + "leave, currently existing" + (3-sp.availablepermits ()) + " a concurrency.
					
				");
			}
			};
		Service.execute (runnable);
* * Run Result: Thread Pool-1-thread-1 Enter, currently has 1 concurrent.
Thread pool-1-thread-1 is about to leave.
The thread pool-1-thread-1 left, and currently has 0 concurrent.
Thread Pool-1-thread-1 entered, there are currently 1 concurrent.
Thread pool-1-thread-1 is about to leave.
The thread pool-1-thread-1 left, and currently has 0 concurrent.
Thread Pool-1-thread-1 entered, there are currently 1 concurrent.
Thread pool-1-thread-3 entered, there are currently 2 concurrent.
Thread pool-1-thread-1 is about to leave.
The thread pool-1-thread-1 left, and currently has 1 concurrent.
Thread pool-1-thread-3 is about to leave.
The thread pool-1-thread-3 left, and currently has 0 concurrent.
Thread pool-1-thread-3 entered, there are currently 1 concurrent.
Thread Pool-1-thread-1 entered, there are currently 2 concurrent.
Thread pool-1-thread-3 is about to leave.
The thread pool-1-thread-3 left, and currently has 1 concurrent.
Thread pool-1-thread-1 is about to leave.
The thread pool-1-thread-1 left, and currently has 0 concurrent.
Thread Pool-1-thread-1 entered, there are currently 1 concurrent.
Thread pool-1-thread-5 entered, there are currently 2 concurrent.
Thread pool-1-thread-1 is about to leave.
The thread pool-1-thread-1 left, and currently has 1 concurrent.
Thread pool-1-thread-5 is about to leave. Thread Pool-1-tHread-5 left, there are currently 0 concurrent.
Thread Pool-1-thread-2 entered, there are currently 1 concurrent.
Thread pool-1-thread-2 is about to leave.
The thread pool-1-thread-2 left, and currently has 0 concurrent.
Thread pool-1-thread-4 entered, there are currently 1 concurrent.
Thread pool-1-thread-4 is about to leave.

 The thread pool-1-thread-4 left, and currently has 0 concurrent. * * 3.

The use case of Cyclicbarrier tool class package com.java5.thread.newSkill;
Import Java.util.concurrent.CyclicBarrier;
Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors; /** * Cyclicbarrier Tool class use case * Application scenario: Each thread waits for each other, to the collective departure * Cyclic: cyclic, Periodic * Barrier: obstruction, barrier/public class Cyclicbarr
		iertest {public static void main (string[] args) {Executorservice service = Executors.newcachedthreadpool ();
		Final Cyclicbarrier cb = new Cyclicbarrier (3);
						for (int i=0;i<3;i++) {Runnable runnable= new Runnable () {@Override the public void run () {try {
						Thread.Sleep ((Long) math.random () *10000); Cb.getnumberwaiting () +1 because the method gets the number of System.out.println ("thread" + thread.currentthread ()) that starts at 0. GetName () + "is about to arrive at the rendezvous point 1 , currently has "+" (cb.getnUmberwaiting () +1) + "has arrived;" + (cb.getnumberwaiting () ==2? " It's all here, keep going. ":" Is waiting.
						"));
						
						Where you want to set up where you await () wait for cb.await ();
						Thread.Sleep ((Long) math.random () *10000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "is about to arrive at the rendezvous point 2, there is currently" + (Cb.getnumberwaiting () +1) + "has arrived;" + (cb.getnumberwaiting () ==2? " It's all here, keep going. ":" Is waiting.
						
						"));
						
						Cb.await ();
						Thread.Sleep ((Long) math.random () *10000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "is about to arrive at the rendezvous point 3, there is currently" + (Cb.getnumberwaiting () +1) + "has arrived;" + (cb.getnumberwaiting () ==2? " It's all here, keep going. ":" Is waiting.
					
						"));
					Cb.await ();
					catch (Exception e) {e.printstacktrace ();
			}
				}
			};
		Service.execute (runnable);
	} service.shutdown ();
* * Run Result: Thread pool-1-thread-2 is about to arrive at the rendezvous point 1, currently 1 have arrived; waiting.
The thread pool-1-thread-3 is about to arrive at the rendezvous point 1, currently 2 has arrived;
The thread pool-1-thread-1 is about to arrive at the rendezvous point 1, now 3 has arrived; it's all here, keep going.
The thread pool-1-thread-2 is about to arrive at the Rendezvous point 2, currently 1 has arrived; The thread pool-1-thread-1 is about to arrive at the Rendezvous point 2, currently 2 has arrived;Waiting.
The thread pool-1-thread-3 is about to arrive at the rendezvous point 2, now 3 has arrived; it's all here, keep going.
The thread pool-1-thread-3 is about to arrive at the rendezvous point 3, currently 1 has arrived;
The thread pool-1-thread-2 is about to arrive at the rendezvous point 3, currently 2 has arrived;
The thread pool-1-thread-1 is about to arrive at the rendezvous point 3, now 3 has arrived; it's all here, keep going. * * 4.

The use case of COUNTDOWNLACTH tool class package com.java5.thread.newSkill;
Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors; /** * COUNTDOWNLACTH Tool class use case * like Countdown counter * latch: LATCH, latch * Application scene: Athlete's match, referee timing.

		A Game games * The following example: Three threads like three athletes, the main thread is like a referee/public class Countdownlatchtest {public static void main (string[] args) {
		
		Executorservice service = Executors.newcachedthreadpool ();
		Set a timer with a number of 1 final countdownlatch Cdorder = new Countdownlatch (1);
		Set a timer with a number of 3 final countdownlatch cdanswer = new Countdownlatch (3);
						for (int i=0;i<3;i++) {Runnable runnable= new Runnable () {@Override the public void run () {try { SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "is preparing to accept the command."
		");				
						/* Open three threads, all waiting here; * How to start the next step ...
						 is to open a main thread to use the countdown () method;
						
						* To carry out the meiosis, reduced to 0 can proceed to the next procedure * * cdorder.await (); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "has accepted the command.
						");
						Thread.Sleep ((Long) math.random () *10000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "responds to command processing results."
						
						");
					
					Countdown () method is to reduce the count on the Counter 1 Cdanswer.countdown ();
					catch (Exception e) {e.printstacktrace ();
			}
				}
			};
		Service.execute (runnable);
			try {thread.sleep (long) math.random () *10000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "is about to publish the command."
			
			");
			
			Cdorder.countdown (); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "sent a command, waiting for the result."

			");
			
			Cdorder.await (); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "has received all response results."
			
			");
		
		Cdanswer.countdown ();
		catch (Exception e) {e.printstacktrace ();
	} service.shutdown (); } 5. Exchanger Tool ClassThe use case package com.java5.thread.newSkill;
Import Java.util.concurrent.Exchanger;
Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors; /** * Exchanger TOOL CLASS use case * Application scenario: Transactional application or game * Two people touch each other, exchanging data/public class Exchangertest {public static void main (
		String[] args) {Executorservice service = Executors.newcachedthreadpool ();
		Final EXCHANGER EXCHANGER = new exchanger ();
					Service.execute (New Runnable () {@Override public void run () {try{String data1 = "Yang"; SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "is changing the data:" +data1+.
					
					");
					
					Thread.Sleep ((Long) math.random () *10000);
					String data2 = (string) exchanger.exchange (data1);
				SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "return the data as:" +DATA2);
		}catch (Exception e) {}}});
					Service.execute (New Runnable () {@Override public void run () {try{String data1 = "Yang Yi"; System.out.prINTLN ("Thread" +thread.currentthread (). GetName () + "is changing the data:" +data1+.
					
					");
					
					Thread.Sleep ((Long) math.random () *10000);
					String data2 = (string) exchanger.exchange (data1);
				SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "return the data as:" +DATA2);

	}catch (Exception e) {}}});

 }

}


 

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.