JAVA 26th (multithreading (5)-communication between multiple threads, java Multithreading

Source: Internet
Author: User

JAVA 26th (multithreading (5)-communication between multiple threads, java Multithreading

1. Inter-thread Communication


Instance code:

Requirement: input a name and gender, and output a name and gender.

Class Resource {String name; String sex;} class Input implements Runnable {Resource r; Input (Resource r) {this. r = r;} public void run () {int x = 0; while (true) {synchronized (r) {if (x = 0) {r. name = "BLF"; r. sex = "male";} else {r. name = "Nini"; r. sex = "female" ;}x = (++ x) % 2 ;}}} class Output implements Runnable {Resource r; public Output (Resource r) {// TODO Auto-generated constructor stubthis. r = r;} public void run () {while (true) {synchronized (r) // both the input and output apply the same lock {System. out. println (r. name + "... "+ r. sex) ;}}} public class Main {public static void main (String [] args) {Resource r = new Resource (); // share the same resource Input in = new Input (r); Output out = new Output (r); Thread t1 = new Thread (in ); thread t2 = new Thread (out); t1.start (); t2.start ();}}

Although the above code solves the problem of multi-thread processing of the same resource, a problem occurs: printing a lot of names and gender before printing the other, and the output cannot be alternate, because: the input thread does not execute the command once after obtaining the execution right. The input thread also has the execution right and keeps assigning values. After switching to the output execution right, the input name and gender are output, however, the output thread does not output data only once. Therefore, many problems such as printing the same name and Gender occur.


Ii. Thread wait/wake-up mechanism:

Use a boolean value to determine whether data exists.

When the input thread executes, it determines whether there is data. If yes, it releases the execution permission, then releases the execution qualification, enters the frozen state, and the output thread executes. After the output, the boolean value is set to false.


Input: if (flag) // wait (); // currently frozen, switch the Output thread flag = true; y (); Output: if (! Flag) wait (); flag = false; // when the flag is set to false, notify () is output. // wake up the input thread

Wait/wake-up mechanism:

Method:

1. wait (); // enables the thread to enter the frozen state. The CPU is released for execution and execution qualifications. The threads that are wait () will be stored in the thread pool. 2. Y (); // wake up any thread in the thread pool. 3. yyall (); // wake up all threads to make them in the running or temporary blocking status. In short, make them qualified for execution.

These methods must be defined in synchronization. These methods are used to operate the thread state. Therefore, you must specify the lock thread on which the thread is located.

(Wait () A lock thread can only wake up the lock thread with notify of lock .)

Understanding: wait () and other methods are defined in the Object class. These methods are the monitor method, and the monitor can be understood as a lock to control the thread under which the lock belongs, the lock can be arbitrary, and all classes inherit from the Object class, so classes such as wait () are defined in the Object.


The following code solves the problem of the above Code and achieves alternate execution of input and output threads.

Class Resource extends Object {String name; String sex; boolean flag = false;} class Input implements Runnable {Resource r; Input (Resource r) {this. r = r;} public void run () {int x = 0; while (true) {synchronized (r) {if (r. flag) {try {r. wait ();} catch (Exception e) {// TODO: handle exception} if (x = 0) {r. name = "BLF"; r. sex = "male";} else {r. name = "Nini"; r. sex = "female";} r. flag = true; r. notify (); x = (++ x) % 2 ;}} } Class Output implements Runnable {Resource r; public Output (Resource r) {// TODO Auto-generated constructor stubthis. r = r;} public void run () {while (true) {synchronized (r) {if (! R. flag) {try {r. wait ();} catch (Exception e) {// TODO: handle exception} System. out. println (r. name + "... "+ r. sex); r. flag = false; r. notify () ;}}} public class Main {public static void main (String [] args) {Resource r = new Resource (); Input in = new Input (r ); output out = new Output (r); Thread t1 = new Thread (in); Thread t2 = new Thread (out); t1.start (); t2.start ();}}

III: Wait for wake-up mechanism code optimization


To be controllable, members of resources should be private and provide external methods.

So the synchronous operation is executed in the Resource class, And the synchronous function is applied.

Class Resource extends Object {private String name; private String sex; private boolean flag = false; public synchronized void set (String name, String sex) {// TODO Auto-generated constructor stubif (flag) {try {this. wait ();} catch (Exception e) {// TODO: handle exception} this. name = name; this. sex = sex; flag = true; this. notify ();} public synchronized void out () {if (! Flag) {try {this. wait ();} catch (Exception e) {// TODO: handle exception} System. out. println (name + ":" + sex); flag = false; this. required y () ;}} 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 ("BLF", "male");} else {r. set ("ninini", "female") ;}x = (++ x) % 2 ;}} class Output implements Runnable {Resource r; public Output (Resource r) {// TODO Auto-generated constructor stubthis. r = r;} public void run () {while (true) {r. out () ;}} public class Main {public static void main (String [] args) {Resource r = new Resource (); Input in = new Input (r ); output out = new Output (r); Thread t1 = new Thread (in); Thread t2 = new Thread (out); t1.start (); t2.start ();}}



In JAVA, which of the following streams is required for multi-thread communication?

D. Pipe stream. This stream is generally used for multithreading.

JAVA multi-thread synchronization

It is very simple. When it is not used, all threads are running this run, because you have no lock, that is to say, there seems to be only one runnable object, one run code block, however, four threads are in use, which is equivalent to 100 books in a room. Individuals can access the room at the same time. Naturally, all four threads are involved, when you lock up, it is equivalent to locking the door when a person enters, and other people cannot. Only when that person comes out, other people can go in. However, there is an endless loop in it. I know that the book has been put into a sack and guessed it. Other people have gone in, so the loop exits directly. In this way, it seems that only one thread is executing.

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.