Java Threading and concurrency programming practices----synchronizer (exchanger, semaphore)

Source: Internet
Author: User
Tags semaphore

Tag: Just swap start pre tor semaphore resource href Rand

first, the Exchange device

A switch provides a synchronization point between threads that can exchange objects. Each thread will go to this

The Exchange () method of the exchanger passes in some objects, matches the partner thread, and accepts the partner object as a return

return value. The java.util.conurrent.exchange<v> implements a switch.

Here is a small example of code:

import java.util.concurrent.exchanger;  import java.util.concurrent.executorservice;   import java.util.concurrent.executors;    public class exchangertest  {        public static void main (String[]  args)  {          executorservice service =  executors.newcachedthreadpool ();          final  Exchanger exchanger = new exchanger ();           service.execute (new runnable () {               public void run ()  {                   try {                                         String data1 =  "Zxx";                      &NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Thread"  + thread.currentthread (). GetName ()  +                          "Changing Data"  + data1 + ";         "              thread.sleep ((Long) (Math.random ( ) (*10000));                       String data2 =  (String) exchanger.exchange (data1);        &Nbsp;              system.out.println (" Thread " + thread.currentthread (). GetName ()  +                         "swapped data for"  + data2 );                   }catch (exception e) {                                          }               }             });           service.execute (new Runnable () {      &nbsP;        public void run ()  {                   try {                                          String data1 =  "LHM";            &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Threads"  +  Thread.CurrentThread (). GetName ()  +                         "Exchanging data"  + data1 + " ;                       thread.sleep((Long) (Math.random () *10000));                                          String data2 =  (String) Exchanger.exchange (data1);                  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Thread"  + thread.currentthread (). GetName ()  +                          "Return the data as" &NBSP;+&NBSP;DATA2);                   }catch (exception e) {                                          }                               }              });            }  }

Second, the signal volume

semaphores maintain a set of licenses to constrain the number of threads that access the restricted resources. When there is no available

License, the thread's fetch attempt is blocked until the other thread releases a license.

The Java.util.concurrent.Semaphor realizes this Synchronizer while conceptualizing the semaphore as a

An object that maintains a set of licenses. He has two constructors:

Semaphore (int permits)

Semaphore (int Permits,boolean Fair)

permits specifies the number of licenses, fair whether to set a fair policy, when set to False, this class does not line

The order of the process to obtain the license to do any guarantee. In particular, intrusion is allowed, meaning that it can be in front of the waiting thread

acquire()assigns a license to the calling thread, which logically means that the new thread puts itself in the waiting thread queue

's head. When fair is set to true, the semaphore is guaranteed for any 获取 thread that invokes the method, as

The order in which they call these methods (i.e., FIFO) to select a thread and obtain a license.

Example code:

Create a Semaphore object and give 3 resources semaphore semaphore = new semaphore (3);//Turn on 10 threads for (int i=0; i<10; i++) {new Thread (new Runn            Bale () {public void run () {//Gets the resource, if the resource is exhausted at this time, blocks until the thread returns the resource Semaphore.acquire ();        Task code ...//Release resources semaphore.release (); }}). Start ();}


Java Threads and concurrent programming practices----synchronizer (exchanger, semaphore)

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.