Java Advanced-Multithreading (2)

Source: Internet
Author: User
Tags semaphore

Block queue:
1) Blockingqueue This interface provides:
Add ()/remove () assumes that when the queue has no data, the data is taken from the queue, or the data in the queue is full,
To add data to the queue, an exception is thrown.
Put ()/take () assumes that when the queue has no data, the data is taken from the queue, or the data in the queue is full,
Data is added to the queue, and a blockage is formed.
Offer ()/poll () returns a special value to the caller, which the developer can use to handle the corresponding
The time-out version number is also available at the same time.
2) interface Implementation
Arrayblockingqueue> a bounded queue implemented by an array with no fairness policy specified by default (that is,
FIFO first-out policy), assuming that the policy does not start, will cause the shared resource to be a greedy thread for a long time to occupy,
A thread that cannot get a resource may die, and such a condition is called starvation;
Linkedblockingqueue> the maximum capacity to optional, the default capacity is the integer maximum, that is, there is no
A situation in which the producer produces a blockage when the queue is increased. This queue is generally used in low-demand situations.
Priorityblockingqueue> the unbounded queue, which is determined by the priority of the thread object to get the CPU operation time, at the same time,
Developers are also able to provide their own comparison device, for example, to extend the same priority thread.
The delayedqueue> is a special priority queue maintained with similar stacks.
1. Stay in the queue for a specified period of time before retrieval.
2. Depending on the dwell time, the maximum dwell time is at the bottom.
3. Only agree to retrieve expired objects when there are no expired objects in the queue. Poll return Null,peek
Gets the object at the top of the stack.
The synchronousqueue> implements every insert operation that must wait for the appropriate removal operation, and the queue is always empty.
When, found in the queue there is something, there will be a corresponding consumption of the instant consumption of these things;
Transferqueue> This interface extends the Blockingqueue. and LinkedTransferQueue provides
A detailed implementation of the interface, which extends the Blockingqueue put method to transfer (), the method
A non-blocking call to timeout. At the same time, the interface provides a number of checks to get waiting consumers.
---------------

/** * * * @author Lean @date: 2014-9-28 */public class Stockexchange {public static void main (string[] args) {Blockingqu Eue<integer> queue=new linkedblockingqueue<integer> (); Saller saller=new Saller (queue); Buyer buyer=new Buyer (queue); Thread[] Sallerthreads=new thread[20]; Thread[] buyerthreads=new thread[20];for (int i = 0; I <sallerThreads.length; i++) {sallerthreads[i]=new Thread (saller ); Sallerthreads[i].start (); buyerthreads[i]=new Thread (buyer); Buyerthreads[i].start ();} try {thread.sleep;} catch (Interruptedexception e) {}system.out.println ("all Thread interrupt!"); for (Thread thread:sallerthreads) {thread.interrupt ();} for (Thread thread:buyerthreads) {thread.interrupt ();}} Static class Saller implements Runnable{private blockingqueue<integer> Mqueue;private boolean shutdownrequest; Public Saller (blockingqueue<integer> queue) {mqueue=queue;} @Overridepublic void Run () {while (shutdownrequest==false) {int quantity= (int) (Math.random () *100); try {MQUEUE.PUT (quantity);//system.out.println ("Saller Order by Thread:" +thread.currentthread (). GetName () + "Quantity:" +quantity );} catch (Interruptedexception e) {shutdownrequest=true;}}}} Static class Buyer implements Runnable{private blockingqueue<integer> Mqueue;private boolean shutdownrequest; Public Buyer (blockingqueue<integer> queue) {mqueue=queue;} @Overridepublic void Run () {while (Shutdownrequest==false) {try {System.out.println ("buyer ORDER by Thread:" + Thread.CurrentThread (). GetName () + "Quantity:" +mqueue.take ()); catch (Interruptedexception e) {shutdownrequest=true;}}}}
---------------

---------------

/** * * @author Lean @date: 2014-9-28 */public class Luckynumbergenerator {public static void main (string[] args) {Trans Ferqueue<string> queue=new linkedtransferqueue<string> (); Thread Producerthread=new Thread (new Producer (queue));p Roducerthread.setdaemon (True);p Roducerthread.start (); int i = 0; I < 20; i++) {thread comsumerthread=new thread (new Comsumer (queue)); Comsumerthread.setdaemon (true); Comsumerthread.start (); try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ()}} System.out.println (Thread.CurrentThread (). Getthreadgroup (). Activecount ()); Static class Producer implements Runnable{private transferqueue<string> mqueue;public Producer (transferqueue <String> queue) {this.mqueue=queue;} Public String product () {return ' Your Lucky number is: ' + ((int) (Math.random () *100)} @Overridepublic void Run () {while (true) {try {if (Mqueue.haswaitingconsumer ()) {Mqueue.put (product ());}} catch ( Interruptedexception e) {e.printstacktrace ();}}}} StatIC class Comsumer implements Runnable{private transferqueue<string> mqueue;public Comsumer (transferqueue< String> queue) {this.mqueue=queue;} @Overridepublic void Run () {try {System.out.println (Mqueue.take ());} catch (Interruptedexception e) {E.printstacktrace ();}}}}
---------------


Synchronizer:

1) Semaphore semaphore
> Specify the number of agents, at a certain time, to see whether there is currently agent processing things,handle the event and release the agent;

/** * * *  @author Lean */public class Bank {private static final int count=100;private static final Semaphore Sema Phore=new Semaphore (2,true);p ublic static void Main (string[] args) {for (int i = 0; i < COUNT; i++) {final int count=i; New Thread () {@Overridepublic void run () {try {if (Semaphore.tryacquire (timeunit.milliseconds)) {try { Teller.getservice (count);} Finally{semaphore.release ();}}} catch (Interruptedexception e) {e.printstacktrace ();}};}. Start ();}} Static class Teller{public static void GetService (int i) {System.out.println ("serving:" +i); try {Thread.Sleep ((long) ( Math.random () *10));} catch (Interruptedexception e) {e.printstacktrace ();}}}}


2) barrier Cyclicbarrier> means that multiple threads stop running after they reach a point (call the Cyclicbarrier object's
Wawit () method) when multiple tasks (to reach the specified number of construction parameters) reach the specified position, run the runnable of the Cyclicbarrier construction parameters;

/** * Barrier (Rendezvous point) *sample: Calculates the sum of squares * @author Lean @date: 2014-9-29 */public class Calculatesum {public static final int count=3; public static int[] Temparray=new Int[count];p ublic static void Main (string[] args) {cyclicbarrier barrier=new Cyclicbarr IER (count,new Runnable () {@Overridepublic void run () {int sum=0;for (int i = 0; i < COUNT; i++) {sum=sum+temparray[i];} SYSTEM.OUT.PRINTLN ("The result is:" +sum);}); for (int i = 0; I <COUNT; i++) {new Thread (new Square (I,barrier)). Start (); System.out.println ("Caculate now ..."); Static class Square implements Runnable{private int initsize;private cyclicbarrier barrier;public Square (int initsize, Cyclicbarrier barrier) {this.initsize=initsize;this.barrier=barrier;} @Overridepublic void Run () {int Result=initsize*initsize;temparray[initsize]=result;try {barrier.await ();} catch ( Interruptedexception e) {e.printstacktrace (),} catch (Brokenbarrierexception e) {e.printstacktrace ();}}}}


3) Inverted count lockout countdownlatch> Construct countdownlatch When you specify the number of reciprocal numbers, calling await () causes the code behind it to block

Call Countdown (), minus-1, when the countdown is 0 o'clock, run the code after the Countdownlatch object await (). Compared to Cyclicbarrier,

Countdownlatch provides manual control of the shielding, more flexible


/** * * @author Lean @date: 2014-9-29 */public class Enhancedstockexchange {public static void main (string[] args) {Bloc Kingqueue<integer> queue=new linkedblockingqueue<integer> (); Countdownlatch startlatch=new Countdownlatch (1); final Countdownlatch stoplatch=new Countdownlatch (200); Producer producer=new Producer (Startlatch, Stoplatch, queue); Saller saller=new Saller (Startlatch, Stoplatch, queue); Thread[] sellerthreads=new thread[100];for (int i = 0; i < sellerthreads.length; i++) {sellerthreads[i]=new Thread (Sall ER); Sellerthreads[i].start ();} Thread[] producerthreads=new thread[100];for (int i = 0; i < producerthreads.length; i++) {producerthreads[i]=new Threa D (producer);p Roducerthreads[i].start ();} Countdown lockout, current countdown is 1, run for example, the following function, the countdown 0;startlatch.countdown (), New Thread (new Runnable () {@Overridepublic void run () {try {// Run await (), pause until the countdown timer is 0stoplatch.await ();} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("All Thread countdown!");}). Start (); try {Thread.sLeep (20);} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("terminating ...");//Run interrupt (), Mstoplatch.countdown () after running the while statement, and a countdown of 1for (thread thread: Sellerthreads) {thread.interrupt ();} for (Thread thread:producerthreads) {thread.interrupt ();} The countdown is 0, running the code behind await () in the Run () method; Stoplatch.countdown ();} Static class Producer implements Runnable{public countdownlatch mstartlatch;public Countdownlatch mstoplatch;private Blockingqueue<integer> Mqueue;private boolean shutdownrequest;public Producer (Countdownlatch startLatch, Countdownlatch stoplatch,blockingqueue<integer> queue) {mstartlatch=startlatch;mstoplatch=stoplatch;mqueue= Queue;} @Overridepublic void Run () {try {mstartlatch.await ();} catch (Interruptedexception e) {e.printstacktrace ();} while (Shutdownrequest==false) {try {mqueue.put (int) (Math.random () * ()))} catch (Interruptedexception e) { Shutdownrequest=true;}} Mstoplatch.countdown ();}} Static class Saller implements Runnable{public Countdownlatch mStArtlatch;public Countdownlatch mstoplatch;private blockingqueue<integer> mQueue;private Boolean Shutdownrequest;public Saller (Countdownlatch startlatch,countdownlatch stoplatch,blockingqueue<integer> Queue) {Mstartlatch=startlatch;mstoplatch=stoplatch;mqueue=queue;} @Overridepublic void Run () {try {mstartlatch.await ();} catch (Interruptedexception e) {e.printstacktrace ();} while (Shutdownrequest==false) {try {System.out.println ("Saller comsume:" +mqueue.take ());} catch (Interruptedexception e) {shutdownrequest=true;}} Mstoplatch.countdown ();}}}




4) Phase Shifter Phaser> Implement barrier-like functions, compared to barrier and inverted count lockout, phaser instance managerprovides a scalable number of waits.

In the process of execution, the dynamic addition of the number of blocks can be called Manager.register (); when Manager.arriveandderegister () is called, all current

wait for the thread to continue running; Manager.arriveandawaitadvance () can be called in the course run;

Wait for other threads; At the same time we can call Manager.getarrivedparties () to see the number of waiting threads;

/** * * @author Lean @date: 2014-9-29 */public class Horserace {private final int number_of_horse=12;private static FINA l int init_parties=1;private static final Phaser manager=new Phaser (init_parties);p ublic static void Main (string[] args) { Check the number of horses in readiness thread racemonitor=new thread (new Racemonitor ()); Racemonitor.setdaemon (true); Racemonitor.start (); new Horserace (). Managerrace ();} private void Managerrace () {arraylist

5) switch exchanger<t>
Type T is a two-thread-switched object, and in some of the same operations, in bulk programming, a class of threads
Responsible for the production of objects, there is a class of programming responsible for consuming objects, for the sharing of data between threads, the previous introduction of the lock
Definition, when we use Java-provided exchanger<t> to transfer objects, there is no need to lock the concept.
Buffers=productexchange.exchanger.exchange (buffers, 1000,timeunit.milliseconds);
The Exchange method parameters of the object pass data from other threads of the thread and return the data returned by other threads

/** * * @author Lean @date: 2014-9-29 */public class Productexchange {public static Exchanger<arraylist<integer&gt ;> exchanger=new exchanger<arraylist<integer>> ();p ublic static void Main (string[] args) {Thread Producerthread=new Thread (New Producer ()); Thread Comsumethread=new Thread (new Comsume ());p Roducerthread.start (); Comsumethread.start (); try {thread.sleep (1000 );} catch (Interruptedexception e) {e.printstacktrace ();} Producerthread.interrupt (); Comsumethread.interrupt ();} private static class Producer implements Runnable{private static arraylist<integer> buffers=new arraylist< Integer> ();p rivate boolean oktorun=true, @Overridepublic void Run () {while (Oktorun) {try {if (Buffers.isempty ()) { (int i = 0; I <10; i++) {Buffers.add ((int) (Math.random () *100));} Thread.Sleep (+); for (int i:buffers) {System.out.print (i+ ",");} System.out.println (""); Buffers=productexchange.exchanger.exchange (buffers, 1000,timeunit.milliseconds);}} catch (interruptedexceptIon e) {oktorun=false;} catch (TimeoutException e) {System.out.println ("Produce time out!");}}} private static class Comsume implements Runnable{private static arraylist<integer> buffers=new arraylist< Integer> ();p rivate boolean oktorun=true, @Overridepublic void Run () {while (Oktorun) {try {if (Buffers.isempty ()) { Buffers=productexchange.exchanger.exchange (buffers); for (int i:buffers) {System.out.print (i+ ",");} System.out.println (""); Thread.Sleep ($); Buffers.clear ();}} catch (Interruptedexception e) {oktorun=false;}}}}

Java Advanced-Multithreading (2)

Related Article

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.