Java learning notes 46 (multithreading 3: communication between threads) and java learning notes

Source: Internet
Author: User

Java learning notes 46 (multithreading 3: communication between threads) and java learning notes

Multiple Threads are processing the same resource, but the tasks of the threads are different. Through some means, each thread can effectively use the resources,

This means: waiting for the wake-up mechanism, also known as inter-thread Communication

Methods involved: wait (), Policy ()

 

Example:

Two threads have one input and one output.

package demo;public class Resource {    public String name;    public String sex;}

Input thread:

Package demo; public class Input implements Runnable {private Resource r = new Resource (); public void run () {int I = 0; while (true) {if (I % 2 = 0) {r. name = "James"; r. sex = "male";} else {r. name = "Li Si"; r. sex = "female" ;} I ++ ;}}}

Output thread:

package demo;public class Output implements Runnable {    private Resource r = new Resource();    public void run(){        while (true) {            System.out.println(r.name+"..."+r.sex);        }    }}

Test class:

package demo;public class ThreadDemo {    public static void main(String[] args) {        Input in = new Input();        Output out = new Output();        Thread tin = new Thread(in);        Thread tout = new Thread(out);                tin.start();        tout.start();    }}

 

After running, it is found that all outputs are null... null

Because the Resource objects created in the input thread and output thread make different

 

Solve the null problem:

Package demo; public class Input implements Runnable {private Resource r; public Input (Resource r) {this. r = r;} public void run () {int I = 0; while (true) {if (I % 2 = 0) {r. name = "James"; r. sex = "male";} else {r. name = "Li Si"; r. sex = "female" ;} I ++ ;}}}
package demo;public class Output implements Runnable {    private Resource r;        public Output(Resource r){        this.r = r;    }        public void run(){        while (true) {            System.out.println(r.name+"..."+r.sex);        }    }}
package demo;public class ThreadDemo {    public static void main(String[] args) {                Resource r = new Resource();                Input in = new Input(r);        Output out = new Output(r);        Thread tin = new Thread(in);        Thread tout = new Thread(out);                tin.start();        tout.start();    }}

 

Another problem is found after running:

Output contains: Zhang San... female or Li Si... male, Gender Error

Cause:

After assigning values to Zhang Sanhe and the male, he continues to assign values to Li Sihe and the female. At this time, the female has not been assigned a value, so he enters the output thread. At this time, the male will be output.

 

So I thought of adding synchronization:

Public void run () {int I = 0; while (true) {synchronized (this) {if (I % 2 = 0) {r. name = "James"; r. sex = "male";} else {r. name = "Li Si"; r. sex = "female" ;} I ++ ;}}}
    public void run() {        while (true) {            synchronized (this) {                System.out.println(r.name + "..." + r.sex);            }        }    }

 

However, the problem has not been solved:

Cause:

The synchronization here has no effect and does not use a lock.

 

Solution:

Use a common lock.

Public void run () {int I = 0; while (true) {synchronized (r) {if (I % 2 = 0) {r. name = "James"; r. sex = "male";} else {r. name = "Li Si"; r. sex = "female" ;} I ++ ;}}}
    public void run() {        while (true) {            synchronized (r) {                System.out.println(r.name + "..." + r.sex);            }        }    }

This is the normal output.

However, there is still a problem. What we hope is that Zhang San and Li Si will appear in a staggered manner. A piece of Zhang San or Li Si will still appear randomly.

 

 

Solution:

Let the input thread assign values first, then let the output thread output, and let the input thread wait. Do not assign values to Li Si. After the output thread ends, allow Li Si to assign values.

The input thread also needs the same method. Wait after the output.

At this time, you need to use the wait for wake-up mechanism:

Input: After the value is assigned, the execution method wait () will always wait.

Output: after printing, before waiting for output, wake up input y () and wait for it () forever.

Input: After being awakened, assign a value again. You must wait y () to wake up the output thread and wait for wait () again.

Loop down in sequence

 

Code implementation:

package demo;public class Resource {    public String name;    public String sex;    public boolean flag = false;}
Package demo; public class Input implements Runnable {private Resource r; public Input (Resource r) {this. r = r;} public void run () {int I = 0; while (true) {synchronized (r) {if (r. flag) {try {r. wait () ;}catch (Exception e) {}} if (I % 2 = 0) {r. name = "James"; r. sex = "male";} else {r. name = "Li Si"; r. sex = "female";} r. flag = true; r. notify () ;} I ++ ;}}}
package demo;public class Output implements Runnable {    private Resource r;    public Output(Resource r) {        this.r = r;    }    public void run() {        while (true) {            synchronized (r) {                if (!r.flag) {                    try {                        r.wait();                    } catch (Exception e) {                    }                }                System.out.println(r.name + "..." + r.sex);                r.flag = false;                r.notify();            }        }    }}
package demo;public class ThreadDemo {    public static void main(String[] args) {        Resource r = new Resource();        Input in = new Input(r);        Output out = new Output(r);        Thread tin = new Thread(in);        Thread tout = new Thread(out);        tin.start();        tout.start();    }}

At this time, it was output by Michael Jacob and James.

Complete

 

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.