Dark Horse programmer ———— The communication between Java threads

Source: Internet
Author: User

------<a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! -------

Multithreading allows us to share a resource at the same time, but what if we need to connect with each other when we share this resource?

Classic example: producer and consumer.

Problem description, the producer of every production of a consumer will take one, and at the same time.

First, Java provides us with a set of wait-and-wake mechanisms to make a connection between threads and threads. A thread is divided into five states: Create, run, block, Freeze, or die. Java provides several methods for state

The wait () method allows the thread to go into a frozen state, yielding the CPU and giving up the lock;

The Notify () method wakes up the thread that enters the frozen state, and Notifyall () is the thread that wakes all.

For the problem, we can set a switch for the producer, if the resource is 0 to allow its production and after the production of the switch off, will not be produced in the producer and wake up the other thread is the consumer thread, of course, on this also use synchronization, in order to ensure that the first producer in the time, other producers will be rejected , the same for consumers.

public static void Main (string[] args) {//Tongbu i=new Tongbu ();//Create extracted synchronization Method object Hjw j=new hjw (i);//Create object that implements Runnable interface BB k= New BB (i); Thread Xc1 =new Thread (j);//thread thread Xc2 =new thread (k); Xc1.setname ("producer"); Xc2.setname ("consumer"); Xc1.start (); Xc2.start ();}} Class tongbu{//extracts two synchronization methods private String name;private int Count=1;boolean flag=false;//defines a bool type to function waiting for wake-up mechanism public synchronized void Set (String name) {//Producer's sync function if (flag) {//already exists on sleep try{wait ();} catch (Exception e) {}}//Otherwise operating code this.name=name+ "---" +count++; System.out.println (Thread.CurrentThread (). GetName () +this.name), flag=true;//change bool value this.notify ();//Wake thread}public synchronized void get () {if (!flag) {//Enter Hibernate try{wait ();} catch (Exception e) {}}//is awakened by the producer System.out.println (Thread.CurrentThread (). GetName () + "---" +this.name); flag=false; This.notify ();//Wake thread}}class HJW implements Runnable{private Tongbu x; HJW (Tongbu x) {//Returns Tongbu object This.x=x;} public void Run () {//Override Run method while (true) {X.set ("cookie");}}} Class BB implements runnable{private Tongbu x; bb (Tongbu x) {//Pass back TongbuObject this.x=x;} public void Run () {//Override the Run method while (true) {X.get ()}}}

This is only for producers and consumers only one thread, if there are multiple threads on this side? It is not as simple as creating several threads, because the Notify method is to wake up the first dormant thread, that is to say, to go back, to produce one, consume two times, and produce more than one.

So how to avoid it? Using the while loop instead of the If loop, each time the thread thaws, the loop starts again instead of going down, so that it avoids multiple executions, but the question is based on the Notify () feature or will cause all threads to wait, I need to wake the other thread, All this time it's going to be notifyall (), waking up all the threads.

public static void Main (string[] args) {//Tongbu i=new Tongbu ();//Create extracted synchronization Method object Hjw j=new hjw (i);//Create object that implements Runnable interface BB k= New BB (i); Thread Xc1 =new Thread (j);//thread thread Xc2 =new thread (k); Xc1.setname ("producer"); Xc2.setname ("consumer"); Xc1.start (); Xc2.start ();}} Class tongbu{//extracts two synchronization methods private String name;private int Count=1;boolean flag=false;//defines a bool type to function waiting for wake-up mechanism public synchronized void Set (String name) {//Producer's sync function while (flag) {//already exists on sleep try{wait ();} catch (Exception e) {}}//Otherwise operating code this.name=name+ "---" +count++; System.out.println (Thread.CurrentThread (). GetName () +this.name), flag=true;//change bool value this.notifyall ();//Wake thread} Public synchronized void get () {while (!flag) {//Enter Hibernate try{wait ();} catch (Exception e) {}}//is awakened by the producer System.out.println (Thread.CurrentThread (). GetName () + "---" +this.name); flag=false; This.notifyall ();//Wake thread}}class HJW implements Runnable{private Tongbu x; HJW (Tongbu x) {//Returns Tongbu object This.x=x;} public void Run () {//Override Run method while (true) {X.set ("cookie");}}} Class BB implements runnable{private Tongbu x; BB (Tongbu x{//Pass back Tongbu object this.x=x;} public void Run () {//Override the Run method while (true) {X.get ()}}}

In fact, the java5.0 version provides a more complete solution for waking up a specified thread. In Java.lang.util.concurrent.locks, a method is provided to replace the lock display with a synchronous synchronized,lock () lock, Unlock () lock, unlock this feature as if the resource is closed, no matter what is done, Because there are exceptions that need to be handled, unlock is placed in finally{}, whereas for the wait () method and notify () in object, the Notifyall () method uses condition's await (), signal () and Signalall () Replace, there is a new condition method in lock, so you can implement operations on the specified thread by creating multiple condition classes.

Dark Horse programmer ———— The communication between Java threads

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.