JAVA multi-thread communication mode, java multi-thread
I. Introduction
This article summarizes my understanding of the communication methods between threads in JAVA multithreading, and mainly discusses the communication between threads in the form of code and text. Therefore, I excerpted some sample code in the book.
2. Inter-thread Communication
① Synchronization
Synchronization means that multiple threads use the synchronized keyword to implement inter-thread communication.
Example:
Public class MyObject {synchronized public void methodA () {// do something ....} synchronized public void methodB () {// do some other thing} public class ThreadA extends Thread {private MyObject object; // omit the constructor @ Override public void run () {super. run (); object. methodA () ;}} public class ThreadB extends Thread {private MyObject object; // The constructor @ Override public void run () {super. run (); object. methodB () ;}} public class Run {public static void main (String [] args) {MyObject object = new MyObject (); // thread A and thread B hold the same object: object ThreadA a = new ThreadA (object); ThreadB B = new ThreadB (object);. start (); B. start ();}}
Because thread A and thread B hold the object of the same MyObject class, although the two threads need to call different methods, they are synchronously executed, for example:Thread B needs to wait until thread A finishes executing the methodA () method before it can execute the methodB () method. In this way, the communication between thread A and thread B is realized.
This method is essentially "Shared Memory" communication. Multiple Threads need to access the same shared variable. Whoever gets the lock (obtains the access permission) can execute it.
② While round robin
The Code is as follows:
1 import java. util. arrayList; 2 import java. util. list; 3 4 public class MyList {5 6 private List <String> list = new ArrayList <String> (); 7 public void add () {8 list. add ("elements"); 9} 10 public int size () {11 return list. size (); 12} 13} 14 15 import mylist. myList; 16 17 public class ThreadA extends Thread {18 19 private MyList list; 20 21 public ThreadA (MyList list) {22 super (); 23 this. list = list; 24} 25 26 @ Override27 public void run () {28 try {29 for (int I = 0; I <10; I ++) {30 list. add (); 31 System. out. println ("added" + (I + 1) + "elements"); 32 Thread. sleep (1000); 33} 34} catch (InterruptedException e) {35 e. printStackTrace (); 36} 37} 38} 39 40 import mylist. myList; 41 42 public class ThreadB extends Thread {43 44 private MyList list; 45 46 public ThreadB (MyList list) {47 super (); 48 this. list = list; 49} 50 51 @ Override52 public void run () {53 try {54 while (true) {55 if (list. size () = 5) {56 System. out. println ("= 5, thread B is about to exit"); 57 throw new InterruptedException (); 58} 59} 60} catch (InterruptedException e) {61 e. printStackTrace (); 62} 63} 64} 65 66 import mylist. myList; 67 import extthread. threadA; 68 import extthread. threadB; 69 70 public class Test {71 72 public static void main (String [] args) {73 MyList service = new MyList (); 74 75 ThreadA a = new ThreadA (service); 76. setName ("A"); 77. start (); 78 79 ThreadB B = new ThreadB (service); 80 B. setName ("B"); 81 B. start (); 82} 83}
In this way, thread A constantly changes the condition, and thread ThreadB continuously checks this condition through the while statement (list. whether size () = 5) is true, thus realizing inter-thread communication. HoweverThis method wastes CPU resources.. It is a waste of resources because the JVM scheduler does not perform "useful" work when it delivers the CPU to thread B for execution, but is constantly testing whether a condition is true.In real life, someone has been watching whether a phone number is on the mobile phone screen, rather than logging in to TA when there is a phone number.For more information about the impact of thread polling, see JAVA multithreading. Does one thread affect another thread when it executes an endless loop?
③ Wait/notify Mechanism
The Code is as follows:
1 import java. util. arrayList; 2 import java. util. list; 3 4 public class MyList {5 6 private static List <String> list = new ArrayList <String> (); 7 8 public static void add () {9 list. add ("anyString"); 10} 11 12 public static int size () {13 return list. size (); 14} 15} 16 17 18 public class ThreadA extends Thread {19 20 private Object lock; 21 22 public ThreadA (Object lock) {23 super (); 24 this. lock = lo Ck; 25} 26 27 @ Override28 public void run () {29 try {30 synchronized (lock) {31 if (MyList. size ()! = 5) {32 System. out. println ("wait begin" 33 + System. currentTimeMillis (); 34 lock. wait (); 35 System. out. println ("wait end" 36 + System. currentTimeMillis (); 37} 38} 39} catch (InterruptedException e) {40 e. printStackTrace (); 41} 42} 43} 44 45 46 public class ThreadB extends Thread {47 private Object lock; 48 49 public ThreadB (Object lock) {50 super (); 51 this. lock = lock; 52} 53 54 @ Override55 public vo Id run () {56 try {57 synchronized (lock) {58 for (int I = 0; I <10; I ++) {59 MyList. add (); 60 if (MyList. size () = 5) {61 lock. using Y (); 62 System. out. println ("a notification has been sent"); 63} 64 System. out. println ("added" + (I + 1) + "elements! "); 65 Thread. sleep (1000); 66} 67} 68} catch (InterruptedException e) {69 e. printStackTrace (); 70} 71} 72} 73 74 public class Run {75 76 public static void main (String [] args) {77 78 try {79 Object lock = new Object (); 80 81 ThreadA a = new ThreadA (lock); 82. start (); 83 84 Thread. sleep (50); 85 86 ThreadB B = new ThreadB (lock); 87 B. start (); 88} catch (InterruptedException e) {89 e. printStackTrace (); 90} 91} 92}
Thread A needs to wait for A condition to meet (list. size () = 5) before executing the operation. Thread B adds an element to the list and changes the size of the list.
How do I communicate between A and B? That is to say, how does thread A know that list. size () is already 5?
The wait () and Y () Methods of the Object class are used here.
When the condition is not met (list. size ()! = 5), thread A calls wait () to discard the CPU and enter the blocking status. --- CPU usage is not as high as ② while polling
When conditions are met, thread B calls notify () to notify thread A. The so-called notification thread A is to wake up thread A and make it run.
One advantage of this method is that the CPU utilization is improved.
However, there are also some disadvantages: for example, thread B executes the command first, and adds five elements at once and calls notify () to send A notification. At this time, thread A still executes the command; when thread A executes and calls wait (), it will never be awakened. Because thread B has been notified and will not be notified later. Note:Too early a notification will disrupt the execution logic of the program.
For more information about wait/notify, refer to: JAVA multi-thread wait/notify