Multi-threaded synchronization (Lock)

Source: Internet
Author: User

Instance

Patterns that mimic producers and consumers

A two-thread first.

Class Producerconsumerdemo{public static void Main (string[] args) {res r=new res (); Pro In=new Pro (R); Cou out=new Cou (R); Thread T1=new thread (in); Thread T2=new thread (out); T1.start (); T2.start ();}} Class Res{private string Name;private int count=1;private boolean flag=false;public synchronized void set (String name) {if (flag) try{wait ();} catch (Exception e) {}this.name=name+ "---" +count++; System.out.println (Thread.CurrentThread (). GetName () + + + + + + producers + + + +this.name); flag=true;this.notify (); Public synchronized void out () {if (!flag) try{wait ();} catch (Exception e) {}system.out.println (Thread.CurrentThread (). GetName () + "consumer" +this.name); flag=false;this.notify ();}} Class Pro implements Runnable{private Res R; Pro (Res R) {this.r=r;} public void Run () {while (true) {R.set ("--commodity--");}}} Class Cou implements Runnable{private Res R; Cou (Res R) {this.r=r;} public void Run () {while (true) {R.out ()}}}

That's OK.

The following will try four threads, two threads of production, two threads consumption;

class producerconsumerdemo{public static void Main (string[] args) {res r=new res (); Pro In=new Pro (R); Cou out=new Cou (R); Thread T1=new thread (in); Thread T2=new thread (in); Thread T3=new thread (out); Thread T4=new thread (out); T1.start (); T2.start (); T3.start (); T4.start ();}} Class Res{private string Name;private int count=1;private boolean flag=false;public synchronized void set (String name) {if (flag) try{wait ();} catch (Exception e) {}this.name=name+ "---" +count++; System.out.println (Thread.CurrentThread (). GetName () + + + + + + producers + + + +this.name); flag=true;this.notify (); Public synchronized void out () {if (!flag) try{wait ();} catch (Exception e) {}system.out.println (Thread.CurrentThread (). GetName () + "consumer" +this.name); flag=false;this.notify ();}} Class Pro implements Runnable{private Res R; Pro (Res R) {this.r=r;} public void Run () {while (true) {R.set ("--commodity--");}}} Class Cou implements Runnable{private Res R; Cou (Res R) {this.r=r;} public void Run () {while (true) {R.out ()}}} 


But the result is more production and less consumption, not the one we want to produce a consumption;

Improved code

class producerconsumerdemo{public static void Main (string[] args) {res r=new res (); Pro In=new Pro (R); Cou out=new Cou (R); Thread T1=new thread (in); Thread T2=new thread (in); Thread T3=new thread (out); Thread T4=new thread (out); T1.start (); T2.start (); T3.start (); T4.start ();}} Class Res{private string Name;private int count=1;private boolean flag=false;public synchronized void set (String name) {WH Ile (Flag) try{wait ();} catch (Exception e) {}this.name=name+ "---" +count++; System.out.println (Thread.CurrentThread (). GetName () + + + + + + producers + + + +this.name); Flag=true;this.notifyall (); Public synchronized void out () {while (!flag) try{wait ();} catch (Exception e) {}system.out.println (Thread.CurrentThread (). GetName () + "consumer" +this.name); flag=false; This.notifyall ();}} Class Pro implements Runnable{private Res R; Pro (Res R) {this.r=r;} public void Run () {while (true) {R.set ("--commodity--");}}} Class Cou implements Runnable{private Res R; Cou (Res R) {this.r=r;} public void Run () {while (true) {R.out ()}}} 


For multiple producers and consumers.

Why define a while judgment tag.

Reason: Let the thread be awakened at once to judge the token.

Why define Notifyall?

Because you need to wake the other thread.

In the case of notify only, it is easy to wake up the thread only, causing all threads in the program to wait.

A multithreaded upgrade solution is available in the

jdk new version. The
replaces the synchronization syschronized with the actual lock operation;
replaces the wait, notify Notifyall in object with the condition object.
The object can be obtained by lock lock. The
implements the action that the party only wakes the other side;

Import Java.util.concurrent.locks.*;class producerconsumerdemo2{public static void Main (string[] args) {res r=new res () ; Pro In=new Pro (R); Cou out=new Cou (R); Thread T1=new thread (in); Thread T2=new thread (in); Thread T3=new thread (out); Thread T4=new thread (out); T1.start (); T2.start (); T3.start (); T4.start ();}} Class res{private String name;private int count=1;private boolean flag=false;private Lock lock=new reentrantlock ();p Riva Te Condition condition_in=lock.newcondition ();p rivate Condition condition_out=lock.newcondition ();p ublic void Set ( String name) throws Interruptedexception{lock.lock (); Try{while (flag) condition_in.await (); this.name=name+ "---" + count++; System.out.println (Thread.CurrentThread (). GetName () + + + + + + producers + + + +this.name); flag=true;condition_out.signal (); Finally{lock.unlock ();//Unlock object Be sure to execute}}public void out () throws Interruptedexception{lock.lock (); Try{while (!flag) Condition_out.await (); System.out.println (Thread.CurrentThread (). GetName () + "consumer" +this.name); flag=false;condition_in.signal ();Finally{lock.unlock ();}}} Class Pro implements Runnable{private Res R; Pro (Res R) {this.r=r;} public void Run () {Try{while (true) {R.set ("--goods--");}} catch (Interruptedexception e) {}}}class Cou implements runnable{private Res R; Cou (Res R) {this.r=r;} public void Run () {Try{while (true) {R.out ()}} catch (Interruptedexception e) {}}}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Multi-threaded synchronization (Lock)

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.