Java thread (3) Producer consumer mode-Thread Synchronization

Source: Internet
Author: User

Introduction

The producer and consumer problems are classic issues in the thread model:Same time periodIntranet sharingSame bucketAs shown in, if the producer stores data into the space and the consumer uses the data, the following situations may occur if the data is not coordinated:

Producer consumer Diagram

The storage space is full, and the producer occupies it. The consumer waits for the producer to let out the space to remove the product. The producer waits for the consumer to consume the product and then adds the product to the space. Wait for each other to cause a deadlock.

Java solves the thread model in three ways

1. Wait and Policy

Package COM. ch. egg; import Java. util. arraylist; import Java. util. list; public class threadegg {private list <Object> eggs = new arraylist <Object> ();/*** if you do not have the lock tag of an object (synchronized ), while attempting to use wait/notify to coordinate and share object Resources, * the application will throw illegalmonitorstateexception. ** @ Param I * @ return */Public synchronized object geteggs (int I) {// if the number of eggs in the disk is 0, wait () is blocked and enters the queue, wait for the producer (put eggs) thread to wake up if (eggs. size () = 0) {try {Wait ();} catch (interruptedexception e) {e. printstacktrace () ;}} object egg = eggs. get (0); eggs. clear (); Using Y (); system. out. println ("get eggs" + I); Return egg;} public synchronized void pugegg (Object egg, int I) {// wait () the queue is blocked and waiting for the consumer (eggs) thread to wake up if (eggs. size ()> 0) {try {Wait ();} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace () ;}} eggs. add (EGG); y (); system. out. println ("put eggs" + I);} static class addthread extends thread {private threadegg; private object egg; Public addthread (threadegg) {This. threadegg = threadegg;} public void run () {for (INT I = 0; I <5; I ++) {threadegg. pugegg (egg, I) ;}} static class getthread extends thread {private threadegg; Public getthread (threadegg) {This. threadegg = threadegg;} public void run () {for (INT I = 0; I <5; I ++) {threadegg. geteggs (I) ;}} public static void main (string [] ARGs) {try {threadegg = new threadegg (); addthread ath = new addthread (threadegg ); getthread threads = new getthread (threadegg); ath. start (); begin. start (); ath. join (); ignore. join ();} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace ();} system. out. println ("over ...... ");}}

2. Await () and signal (), that is, the thread lock method.

Package COM. ch. egg; import Java. util. using list; import Java. util. concurrent. locks. condition; import Java. util. concurrent. locks. lock; import Java. util. concurrent. locks. reentrantlock;/*** reentrantlock Is A reentrant mutex lock. * It has the same basic behavior and semantics as the implicit monitor lock accessed by the Synchronized Method and statement, but it is more powerful. ** condition splits the object monitor methods (wait, policy, and policyall) into completely different objects. * This allows you to combine these objects with any lock implementation, multiple waiting sets (wait-set) are provided for each object ). * Lock replaces the Synchronized Method and statement, and condition replaces the object monitor method. ** @ Author ch **/public class threadegglock {private callback list <Object> eggs = new callback list <Object> (); Private int max = 1; private final lock = new reentrantlock (); private final condition full = lock. newcondition (); private final condition empty = lock. newcondition (); Private int COUNT = 0; Public void start () {new producer (). start (); new consumer (). start ();} public static void main (string [] ar GS) throws exception {threadegglock S2 = new threadegglock (); s2.start ();} class producer extends thread {public void run () {While (count <5) {lock. lock (); try {While (eggs. size () = max) {// The plate is full of system. out. println ("------ warning: the plate is full! "); Full. await ();} object egg = new object (); If (eggs. add (EGG) {system. out. println ("put eggs" + count); empty. signal () ;}} catch (interruptedexception IE) {system. out. println ("producer is interrupted! ");} Finally {lock. unlock () ;}}} class Consumer extends thread {public void run () {While (count <= 5) {lock. lock (); try {While (eggs. size () = 0) {// The plate is empty system. out. println ("------ warning: the plate is empty now"); empty. await ();} eggs. removelast (); system. out. println ("Take eggs" + count); count ++; full. signal ();} catch (interruptedexception IE) {system. out. println ("consumer is interrupted! ") ;}Finally {lock. Unlock ();}}}}}

3. Queue Blocking

Package COM. ch. egg; import Java. util. concurrent. define blockingqueue; public class threadeggblock {// create a blocking queue/*** a blocking queue in any range based on linked nodes. * This queue is sorted by FIFO (first-in-first-out. * The queue header is the element with the longest time in the queue, and the tail of the queue is the element with the shortest time in the queue. ** The new element is inserted at the end of the queue, and the elements in the queue header are obtained after the queue obtaining operation. * The throughput of the link queue is usually higher than that of the array-Based Queue, but its predictable performance is lower in most concurrent applications. */Private linkedblockingqueue <Object> queue_eggs = new linkedblockingqueue <Object> (1); private int COUNT = 1; Public void start () throws interruptedexception {producer = new producer (); consumer consumer = new consumer (); producer. start (); consumer. start ();} public static void main (string [] ARGs) throws exception {threadeggblock S3 = new threadeggblock (); s3.start ();} class producer extends threa D {public void run () {While (count <15) {try {Egg = New egg (string. valueof (count); queue_eggs.put (EGG); system. out. println ("put eggs" + egg. getname (); count ++;} catch (interruptedexception e) {system. out. println ("producer is interrupted! ") ;}}} Class Consumer extends thread {public void run () {While (count <= 15) {try {// retrieve an object Egg = (EGG) queue_eggs.take (); system. out. println ("Fetch eggs" + egg. getname ();} catch (interruptedexception e) {system. out. println ("producer is interrupted! ") ;}}} Class egg {private string name; Public egg (string name) {This. name = Name;} Public String getname () {return name;} public void setname (string name) {This. name = Name ;}}}

Summary:

1. It is very important to deal with multi-threaded synchronization and mutex. The famous producer-consumer example is a classic example, which is required for multithreading in any language.

2. The principles of synchronization are the same among the three methods, which are locking, blocking, and awakening the exclusive space. The first method is more traditional, the second method is the most flexible, and the third method is the simplest, only storage and access are required. The thread synchronization operation is handled by the linkedblockingqueue. 

Thread Synchronization Summary

1. The purpose of thread synchronization is to protect the destruction of resources when multiple threads access a resource. 2. The thread synchronization method is implemented through locks. Each object has only one lock, which is associated with a specific object. Once the thread acquires the object lock, other threads accessing the object will no longer be able to access other Synchronization Methods of the object. 3. for static synchronization methods, the lock is for this class, and the lock object is the class object of this class. Static and non-static method locks do not interfere with each other. A thread acquires the lock. When a synchronization method of another object is accessed in a synchronous method, the two Object locks are obtained. 4. For synchronization, always understand the object on which the synchronization is performed.

5. When using the synchronized keyword, try to avoid using the sleep or yield method in the synchronized method or synchronized block, because the synchronized block occupies the object lock, when you rest, other threads can only be executed after you wake up. It not only seriously affects efficiency, but also is not logical. Similarly, it is meaningless to call the yeild method in the synchronization program block to make the CPU resources available. Because you occupy the lock, other mutex threads still cannot access the synchronization program block. Of course, threads unrelated to the synchronization program block can get more execution time. 6. Write thread-safe classes. always pay attention to making correct judgments on the logic and security of competing multiple threads to access resources, and analyze "Atomic" operations, during the atomic operation, other threads cannot access competing resources. 7. When multiple threads wait for the lock of an object, threads that have not obtained the lock will be blocked. 8. deadlocks are caused by mutual lock wait between threads. Once a deadlock occurs in the program, the program will die. Java thread depth analysis: http://lavasoft.blog.51cto.com/62575/27069

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.