1. Introduction
This summary of my understanding of the communication between threads in JAVA multi-threaded format mainly discusses communication between threads in a code-combined with text, so I excerpted some example codes in the book.
2. Communication method between threads
① Synchronization
The synchronization mentioned here refers to multiple threads using the synchronized keyword to realize communication between threads.
Reference 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;//Omit 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); a.start(); b.start(); }}Since thread A and thread B hold the object object of the same MyObject class, although these two threads need to call different methods, they are executed synchronously. For example, thread B needs to wait for thread A to execute the methodA() method before it can execute the methodB() method. In this way, thread A and thread B realize communication.
This method is essentially "shared memory" communication. Multiple threads need to access the same shared variable, and whoever gets the lock (obtains access rights), can execute it.
②While polling method
The code is as follows:
import java.util.ArrayList;import java.util.List;public class MyList { private List<String> list = new ArrayList<String>(); public void add() { list.add("elements"); } public int size() { return list.size(); }}import mylist.MyList;public class ThreadA extends Thread { private MyList list; public ThreadA(MyList list) { super(); this.list = list; } @Override public void run() { try { for (int i = 0; i < 10; i++) { list.add(); System.out.println("Added" + (i + 1) + "elements"); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } }}import mylist.MyList;public class ThreadB extends Thread { private MyList list; public ThreadB(MyList list) { super(); this.list = list; } @Override public void run() { try { while (true) { if (list.size() == 5) { System.out.println("==5, thread b is ready to exit"); throw new InterruptedException(); } } } catch (InterruptedException e) { e.printStackTrace(); } }}import mylist.MyList;import extthread.ThreadA;import extthread.ThreadB;public class Test { public static void main(String[] args) { MyList service = new MyList(); ThreadA a = new ThreadA(service); a.setName("A"); a.start(); ThreadB b = new ThreadB(service); b.setName("B"); b.start(); }}In this way, thread A constantly changes the conditions, and thread ThreadB constantly detects whether this condition (list.size()==5) is true through the while statement, thereby realizing communication between threads. But this method will waste CPU resources. The reason why it wastes resources is that when the JVM scheduler handes the CPU to thread B for execution, it does not do any "useful" work, but is just constantly testing whether a certain condition is true. It's similar to in real life, someone keeps looking at whether the phone is coming on the screen of his mobile phone, instead of: Doing something else, when a phone is coming, the ringing will notify him that the phone is coming.
③wait/notify mechanism
The code is as follows:
import java.util.ArrayList;import java.util.List;public class MyList { private static List<String> list = new ArrayList<String>(); public static void add() { list.add("anyString"); } public static int size() { return list.size(); }}public class ThreadA extends Thread { private Object lock; public ThreadA(Object lock) { super(); this.lock = lock; } @Override public void run() { try { synchronized (lock) { if (MyList.size() != 5) { System.out.println("wait begin " + System.currentTimeMillis()); lock.wait(); System.out.println("wait end " + System.currentTimeMillis()); } } } catch (InterruptedException e) { e.printStackTrace(); } }}public class ThreadB extends Thread { private Object lock; public ThreadB(Object lock) { super(); this.lock = lock; } @Override public void run() { try { synchronized (lock) { for (int i = 0; i < 10; i++) { MyList.add(); if (MyList.size() == 5) { lock.notify(); System.out.println("Notified"); } System.out.println("Added" + (i + 1) + "elements!"); Thread.sleep(1000); } } } catch (InterruptedException e) { e.printStackTrace(); } }}public class Run { public static void main(String[] args) { try { Object lock = new Object(); ThreadA a = new ThreadA(lock); a.start(); Thread.sleep(50); ThreadB b = new ThreadB(lock); b.start(); } catch (InterruptedException e) { e.printStackTrace(); } }}Thread A must wait for a certain condition to be satisfied before performing the operation. Thread B adds elements to the list and changes the size of the list.
How do A and B communicate? In other words, how does thread A know that list.size() is already 5?
Here we use the wait() and notify() methods of the Object class.
When the condition is not met (list.size() !=5), thread A calls wait() to abandon the CPU and enters a blocking state. ---Do not take up CPU like ②while polling
When the condition is met, thread B calls notify() to notify thread A. The so-called notification thread A is to wake up thread A and let it enter a runnable state.
One advantage of this method is that the CPU utilization has been improved.
But there are some disadvantages: for example, thread B executes first, adds 5 elements at once and calls notify() to send a notification, and thread A still executes; when thread A executes and calls wait(), it will never be awakened. Because Thread B has already issued a notification and will not issue any notification in the future. This shows that the notification is too early and will disrupt the execution logic of the program.
The above article deeply understands the communication method between JAVA multi-threaded threads is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.