Communication between threads

Source: Internet
Author: User
Tags thread class

First, why should the thread communicate?

1. When multiple threads are executing concurrently, the CPU is randomly switching threads by default, and when we need more than one thread to do a task together ,

And we want them to do it regularly, so there 's a need for some coordinated communication between the multiple threads to help us achieve a multi-threaded operation together with a single piece of data .

2. Of course, if we do not use thread communication to operate the same data together using multithreading, though it can be achieved,

But to a large extent will cause multi-threading between the same shared variable contention, so the words are bound to cause a lot of errors and losses!

3. That's why we're leading the communication between the threads,多线程之间的通信能够避免对同一共享变量的争夺。

 

Second, what is thread communication?

Multiple threads are working on the same resource , and the task is different, requiring thread communication to help resolve the use or operation of the same variable between threads.

Is that multiple threads avoid contention for the same shared variable while manipulating the same data .

We then elicit the wait-and-wake mechanism : (Wait (),notify ())

is to wait until the other threads have finished executing their specified code and thenwake them up (notify) after a thread has made a specified operation;

(1) Wait () method:

causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method.

The thread calls the Wait () method, frees its ownership of the lock, and waits for another thread to notify it (the notification is in the Notify () or Notifyall () method) so it can regain ownership of the lock and resume execution.

To ensure that you have a lock when you call the Wait () method, the call to the wait () method must be placed in the synchronized method or synchronized block.

(2) Notif () method:

 notify()方法会唤醒一个等待当前对象的锁的线程。唤醒在此对象监视器上等待的单个线程。

(3)notifAll()方法:
  notifyAll()方法会唤醒在此对象监视器上等待的所有线程。
  
(4)如果多个线程在等待,它们中的一个将会选择被唤醒。这种选择是随意的,和具体实现有关。(线程等待一个对象的锁是由于调用了wait方法中的一个)

 notify()方法应该是被拥有对象的锁的线程所调用。

(5)以上方法都定义在类:Object中

1.因为,这些方法在操作同步中的线程的时候,都必须标示其所操作线程所持有的锁(被该锁的对象调用),

而只有同一个对象监视器下(同一个锁上)的被等待线程,可以被持有该锁的线程唤醒,(无法唤醒不同锁上的线程)

2.所以,等待和唤醒的必须是同一个对象的监视器①下(同一个锁上)的线程。
而锁可以是任意已近确定的对象, 能被任意对象调用的方法应当定义在 Object类中。

注:
监视器(锁):同一个对象的监视器下(同一个锁上)的线程,一次只能执行一个:就是拥有监视器所有权(持有锁)的那一个线程。 

Third, the implementation of the small demo of thread communication

      

 As the public says, there are vivid examples of thread communication: producers---Consumers are one of the most obvious examples. Then we'll hit a simple little demo about the producer and the consumer to demonstrate the thread's communication:

 (1) Bread classes (production and consumption methods are in it.)

/** * @functon Thread Communication * @author Warm (nickname: The top of the sink) * @time 2017.12.5 */package threadmessage;public class Breads {//Bread I    d private int bid;        Number of loaves private int num; The method of producing bread (because it is a demo, easy to understand, the Synchronized keyword added to the method above OH) public synchronized void Produc () {//When the number of bread is not 0 o'clock, this method                In the wait state if (0! = num) {try {wait ();//wait} catch (Interruptedexception e) {            E.printstacktrace (); }}//When the quantity of bread is 0 o'clock, then the bread is started. num = num +1;//number plus 1 bid = bid + 1;//id of course also has to add 1 String threa        Dname = Thread.CurrentThread (). GetName (); System.out.println (threadname+ "produced a bread numbered" +bid+ "!        ");        Notify ();//When execution is complete, go to wake up other waiting threads}//Consume bread method public synchronized void consume () {//when the number of loaves is 0 o'clock, the method is in a wait state if (num = = 0) {try {wait ();//wait} catch (Interruptedexception e) {/ /TODO auto-generated Catch block E.printStackTrace ();         }}//consumed bread, so the amount of bread dropped to 0 num = num-1;//number minus 1 String name1 = Thread.CurrentThread (). GetName ();        System.out.println (name1+ "bought a loaf of bread numbered" +bid);    Notify ();//When execution is complete, go to wake other waiting threads}//set and get method public int getbid () {return bid;    } public void Setbid (int bid) {this.bid = bid;    } public int Getnum () {return num;    } public void setnum (int num) {this.num = num;        }//Public breads (int bid, int num) {super ();        This.bid = bid;    This.num = num;        }//non-parametric construction public breads () {super (); TODO auto-generated constructor stub}}

(2) Types of bread production

/** * @functon Thread Communication Production class (Inherit thread Class)  * @author Warm (nickname: The top of the sink) * @time 2017.12.5  */package Threadmessage;public class Producer extends thread{        //Get bread class    private breads bre;    Non-parametric construction public    producer () {        super ();    }    Structure public    producer (breads Bre) {        super ();        This.bre = bre;    }    The set and Get methods public    Breads Getbre () {        return bre;    }    public void Setbre (breads bre) {        this.bre = bre;    }    Inheritance overrides the Run method    @Override public    void Run () {        Pro ();    }        Production    of bread private void Pro () {        //the system default cycle produces 20 breads for        (int i = 0; I <20; i++) {            try {                //sleeps 0.3 seconds (Demo effect                Thread.CurrentThread () () (). Sleep (            interruptedexception e) {                         e.printstacktrace () ;            }            The method of making bread in the bread class is called            Bre.produc ();}}}    

   (3) Types of bread consumption

/** * @functon Thread communication consumption class (Inherit thread Class)  * @author Warm (nickname: The top of the sink) * @time 2017.12.5  */package Threadmessage;public class Consume extends thread{    //Get bread class    private breads bre;        The set and Get methods public    Breads Getbre () {        return bre;    }    public void Setbre (breads bre) {        this.bre = bre;    }        Inheritance overrides the Run method    @Override public    void Run () {        con ();    }        Consumer bread    private void con () {        //consistent with the producer, the system by default cycle produces 20 breads (producing several, consuming several) for        (int i = 0;i<20;i++) {            try {                //sleep for 0.3 seconds (demo effect required, can not add)                thread.currentthread (). Sleep (), and            catch (Interruptedexception e) {                E.printstacktrace ();            }            The method of making bread in the bread class is called            Bre.consume ();        }    }    Structure public    consume (breads bre) {        super ();        This.bre = bre;    }    Non-parametric construction public    consume () {        super ();    }}

(4) Test class

/** * @functon thread Communication Test class  * @author warm (nickname: The top of the sink) * @time 2017.12.5  */package threadmessage;public class Testbreads { C4/>public static void Main (string[] args) {                //new a bread class        breads bre = new breads ();                New A producer class        producer Proth = new producer (BRE);        New A consumer class        consume Conth = new consume (BRE);                New A thread that contains the consumer class threads        t1 = new Thread (Proth, "producer");                New A thread that contains the producer class threads        t2 = new Thread (conth, "consumer");                Start thread        t1.start ();        T2.start ();            }}

(5) Demo effect (due to too much data, the middle is omitted OH)

The producer produced a loaf of bread numbered 1! The consumer bought a bread number for 1 producers to produce a loaf numbered 2! The consumer bought a bread number for 2 producers to produce a loaf numbered 3! The consumer bought a bread number of 3

...
...

The producer produced a loaf of bread numbered 17!
The consumer bought a bread number of 17
The producer produced a loaf of bread numbered 18!
The consumer bought a bread number of 18
The producer produced a loaf of bread numbered 19!
The consumer bought a bread number of 19
The producer produced a loaf of bread numbered 20!
The consumer bought a bread number of 20

as shown above, the case shows that the producer consumers are using wait () and Notify () These two methods, through the sleep and wake mechanism of communication, to complete two different threads to operate the unified data between the communication,

When a producer produces a loaf of bread, it goes to sleep and then immediately awakens the consumer, as if to say, "You go buy it, I produce it, and then the consumer will fart to buy the bread, when he finished eating the bread,

Will fall asleep, and then immediately awaken the producer, as if to say to him, you reproduce a bar, I ate, then the producer ... This cycle repeats until the For loop ends.

  

Iv. multiple producers and consumers

When we create multiple producers and consumers, one of the problems with the code above is that they won't be able to wake up to which one, so we're going to use thenotifAll()方法。

Then the code will not be sent one by one, and the above, the only difference is that in the bread class if replaced by a while loop judgment, Notif () replaced by Notifall ().

Then we will write to you a number of producers and consumers of the test class:

  (1) test class for multiple producers and consumers

/** * @functon thread Communication Test class  * @author warm (nickname: The top of the sink) * @time 2017.12.5  */package threadmessage;public class Testbreads { C2/>public static void Main (string[] args) {                //new a bread class        breads bre = new breads ();                New A producer class        producer Proth = new producer (BRE);        New A consumer class        consume Conth = new consume (BRE);                New three threads that contain consumer classes thread        t1 = new Thread (Proth, "producer 1");        thread t3 = new Thread (Proth, "producer 2");        Thread T5 = new Thread (Proth, "producer 3");                New three threads that contain the producer class thread        t2 = new Thread (conth, "Consumer 1");        thread T4 = new Thread (conth, "Consumer 2");        Thread T6 = new Thread (conth, "Consumer 3");                Start thread        t1.start ();        T2.start ();        T3.start ();        T4.start ();        T5.start ();        T6.start ();    }}

 (2) demonstrate multiple producer and consumer communication effects

Producer 1 produced a loaf numbered 1! Consumer 3 bought a loaf of bread numbered 1 producer 2 produced a loaf numbered 2! Consumer 2 bought a loaf of bread numbered 2 producer 3 produced a loaf numbered 3! Consumer 1 bought a loaf of bread numbered 3 producer 1 produced a loaf numbered 4! Consumer 3 bought a bread number of 4 ... Producer 3 produced a loaf numbered 56! Consumer 3 bought a loaf of bread numbered 56 producer 2 produced a loaf numbered 57! Consumer 1 bought a loaf of bread numbered 57 producer 1 produced a loaf numbered 58! Consumer 2 bought a loaf of bread numbered 58 producer 3 produced a loaf numbered 59! Consumer 3 bought a loaf of bread numbered 59 producer 2 produced a loaf numbered 60! Consumer 1 bought a bread number of 60

As shown above, we have created three producers and three consumers, so our for loop is three times, which will produce and consume 60 loaves of bread;

When the process starts, a producer thread is randomly turned on to produce a loaf of bread and then into a slumber, and then randomly wakes up a consumer thread,

Then consumed the bread that had just been produced and fell asleep again, randomly waking up a producer thread ... Round and round until the end.

Communication between 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.