Inter-Threading Communication problem Learning

Source: Internet
Author: User

Methods involved in inter-thread communication
    Multiple threads are working on a uniform resource, but the tasks are different, requiring inter-thread communication.

    WAIT/wake mechanisms involve methods:
    1. Wait (): The thread is frozen and the wait thread is stored in the thread pool.
    2. Notify (): Wakes up a thread in the thread pool (any one is possible).
    3. Notifyall (): Wakes up all threads in the thread pool.

    P.S.
    1, these methods must be defined in synchronization because they are methods used to manipulate thread state.
    2, it is necessary to know exactly which locked thread is in operation.
    3, wait and sleep differences.
         1) Wait can be specified without specifying a time. Sleep must specify a time.
         2) in synchronization, the CPU execution and lock processing are different.
         wait: Release execution, release lock.
         sleep: Release execution and do not release locks.

    Why the threading method Wait, notify, notifyall are defined in the object class, because these methods are the methods of the monitor, and the monitor is actually a lock. The
lock can be any object, and any object invocation must be in the object class.

    Producer-consumer issues:

Class resource{private String name;
       Private String sex;

       Private Boolean flag = false;
                         Public synchronized void set (String name,string sex) {if (flag) try{
                  This.wait ();
                  } catch (Interruptedexception e) {e.printstacktrace ();
             } this.name = name;
             This.sex = sex;
             Flag = true;
      This.notify (); synchronized void out () {if (!flag) try{th
                  Is.wait ();
                  } catch (Interruptedexception e) {e.printstacktrace (); } System.
             OUT.PRINTLN (name + "..." + sex);
             Flag = false;
     This.notify ();
      }}//Input class input implements runnable{Resource R;
      Input (Resource r) {THIS.R = R; } public void Run() {int x = 0;
                  while (true) {if (x = = 0) {R.set ("Mike", "male");
                  } else{R.set ("Lili", "female");
            } x = (x + 1)%2;

      }}}//Outputs class output implements runnable{Resource R;
      Output (Resource r) {THIS.R = R;
            public void Run () {while (true) {r.out (); }}} class Resourcedemo {public static void main (string[] args) {//Create resource Resource
             R = new Resource ();
            Create task Input in = new input (r);
             Output out = new output (r);
            Create thread, execute path thread t1 = new thread (in);
             Thread t2 = new Thread (out);
            Turn on thread T1.start ();
      T2.start ();
 }
}

Multi-producer-multi-consumer issues:

Class resource{private String name;
       private int count = 1;

       Private Boolean flag = false;
                  Public synchronized void Set (String name) {if (flag) try{wait ();
                  } catch (Interruptedexception e) {e.printstacktrace ();
             } this.name = name + count;
             count++; System.out.println (Thread.CurrentThread (). GetName () + "... Producer ... "+ this.
             name);
            Flag = true;
       Notify ();
                  Public synchronized void out () {if (!flag) try{wait ();
                  } catch (Interruptedexception e) {e.printstacktrace ();
            } flag = false;
            Notify (); System.out.println (Thread.CurrentThread (). GetName () + "... Consumer ... "+ this.
      name);
     }} class Producer implements runnable{ Private Resource R;
      Producer (Resource r) {THIS.R = R;
            public void Run () {while (true) {R.set ("roast duck");
      }}} class Consumer implements runnable{private Resource R;
      Consumer (Resource r) {THIS.R = R;
            public void Run () {while (true) {r.out (); }}} class Producerconsumerdemo {public static void main (string[] args) {Resource r = new Res
            Ource ();
            Producer Pro = new Producer (r);

            Consumer con = new Consumer (r);
            Thread t0 = new Thread (PRO);
            thread T1 = new Thread (PRO);
            Thread t2 = new Thread (con);
            thread t3 = new Thread (con);
            T0.start ();
            T1.start ();
            T2.start ();
      T3.start (); 
 }
}

Cause Analysis: The process of obtaining the above results is analyzed as follows: 1. Thread Thread-0 gets to CPU execution and locks, produces roast duck 3298, sets flag to true. Then, Thread-0 again acquires the CPU execution, because flag is true, so the wait method is executed, blocking. Thread-1 then gets the CPU execution, and because flag is true, the wait method is executed and also blocked.

2. Thread Thread-3 gets the CPU execution right and lock, consumes roast duck 3298, sets flag to false. Then, the thread Thread-0 is awakened, but the thread is not acquired to the lock, but Thread-3 then gets the CPU execution and the lock, but at this point flag is false, so the Thread-3 is blocked. The following thread Thread-2 then acquires the CPU execution and lock, however flag is false at this point, so Thread-2 is also blocked.

3. Thread Thread-0 get CPU execution right and lock, do not need if sentence judgment, directly produce roast duck 3299, then wake thread Thread-1 get to CPU execution right and lock, do not need if sentence judgment, direct production roast duck 3300. Thus causing the roast duck 3299 has not been consumed, the direct production of roast duck 3300 case.
Due to the If judgment tag, only once will cause the wrong thread to run, and a data error condition occurs.     It is changed into a while judgment mark, the thread obtains the CPU execution right and the lock, will re-determine whether has the running condition. The Notify method can only wake up one thread, which is meaningless if the party wakes up the party. And while judging the token +notify will cause a deadlock. notifyall resolves an issue in which the thread of this party will surely wake the other thread.
P.S. While judging the token +notify will lead to a deadlock example: if you modify the If judgment mark in the above code to Wile judgment mark, there will be a deadlock phenomenon, the first 2 steps are consistent with the original. The 3rd step is as follows: 3. The thread Thread-0 obtains the CPU execution right and the lock, passes the while statement to judge, directly produces the roast duck 3299, sets the flag to true. It then wakes up the thread Thread-1 to get the CPU execution and lock, not to be judged by the while statement, blocking. Thread Thread-0 and get to the CPU execution right and lock, pass the while statement judgment, also block, at this time Thread-0, 1, 2, 3 are blocked, so deadlock.

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.