java-Multithreading (Advanced)

Source: Internet
Author: User
Tags semaphore

Blocking queues:
1) Blockingqueue This interface provides:
Add ()/remove () If the queue has no data, fetch data from the queue, or the data in the queue is full,
Adds data to the queue, an exception is thrown.
Put ()/take () If 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, blocking is formed.
The Offer ()/poll () returns a special value to the caller, which the developer can handle accordingly.
A time-out version is also available.
2) interface Implementation
Arrayblockingqueue> a bounded queue implemented by an array with no fairness policy specified by default (that is,
FIFO first-out policy), if the policy is not started, it 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, a condition known as starvation;
Linkedblockingqueue> the maximum capacity to optional, the default capacity is the integer maximum, that is, there is no
A situation in which a producer is blocked when it joins a queue. This queue is generally used in low-demand situations.
Priorityblockingqueue> the unbounded queue, which is determined by the priority of the thread object to obtain the CPU operating time, and
Developers can also provide their own comparators, such as the same extension of 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. Sort by dwell time, the longest dwell time is at the bottom.
3. Only allowed 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 each insert operation that must wait for the corresponding removal operation, and the queue is always empty.
When, found in the queue there is something, there will be a corresponding consumption of the instantaneous consumption of these things;
Transferqueue> This interface extends the Blockingqueue. and LinkedTransferQueue provides
interface, which extends the Blockingqueue put method to transfer (), the method
is a non-blocking call that timed out. At the same time, the interface provides a quantity detection 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 reach a point and stop execution (calling the Cyclicbarrier object's
Wawit () method) executes the runnable of the Cyclicbarrier construction parameter when multiple tasks (to the specified number of construction parameters) reach the specified position;

/** * 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 countdown, call await (), the countdown plus 1,
Called, Countdown (), minus-1, when the countdown is 0 o'clock, executes the code after the await () in the Run () method.


/** * * @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, perform the following function, 0;startlatch.countdown (), New Thread (new Runnable () {@Overridepublic void run () {try {//execute await (), Countdown 201;stoplatch.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 ...");//Executes interrupt (), executes the Mstoplatch.countdown () after the while statement, and the inverse is 1for (thread thread: Sellerthreads) {thread.interrupt ();} for (Thread thread:producerthreads) {thread.interrupt ();} The countdown is 0 and executes the code after the 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 running, dynamically increasing the number of blocks can be called Manager.register (); when Manager.arriveandderegister () is called, all current

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

Wait for other threads, and 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>
The type T is a two-thread-switched object, and in bulk programming for some of the same operations, one of the class threads
Responsible for the production of objects, another type of programming is responsible for consuming objects, for sharing data between threads, the previous introduction of the lock
The definition of a lock is not required when we use Java-provided exchanger<t> to transfer objects.
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-Multithreading (Advanced)

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.