First, introduce
This concludes my understanding of the way of communication between Java multithreaded threads, mainly in the form of code combined with text to discuss the communication between threads, so excerpt some of the book's sample code.
Second, the way of communication between threads
① Sync
Synchronization here refers to the way multiple threads use the Synchronized keyword to communicate 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 {
p Rivate MyObject object;
Omitting the construction method
@Override public
void Run () {
super.run ();
Object.methoda ();
}
public class Threadb extends Thread {
private MyObject object;
Omitting the construction method
@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 ();
}
Because thread A and thread B hold object objects of the same MyObject class, although the two threads need to invoke different methods, they are executed synchronously, for example: thread B needs to wait for thread A to execute the MethodA () method before it executes the MethodB () method. This enables both thread A and thread B to communicate.
This way, in essence, is the "shared memory" type of communication. Multiple threads need access to the same shared variable, who gets the lock (access rights), and who can execute it.
How to ②while polling
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 {= 0; I < i++) {list.add ();
System.out.println ("added" + (i + 1) + "element");
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 () {a try {while (true) {if (list.size () = 5) {SYSTEM.OUT.P
Rintln ("==5, thread B ready to exit"); throw newInterruptedexception ();
A 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 condition, and the thread threadb to detect whether the condition (list.size () ==5) is established through the while statement, thus enabling the communication between threads. But this approach wastes CPU resources. It is a waste of resources because the JVM Scheduler is not doing "useful" work when the CPU is handed over to thread B, but is constantly testing whether a condition is true or not. Just like in real life, someone has been looking at the phone screen to see if there is a phone, instead of: doing something else, when there is a call, the bell to notify Ta phone.
③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) {Sys
TEM.OUT.PRINTLN ("Wait Begin" + system.currenttimemillis ());
Lock.wait ();
SYSTEM.OUT.PRINTLN ("Wait End" + system.currenttimemillis ());
A 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 < i++) {mylist.add ();
if (mylist.size () = = 5) {lock.notify ();
System.out.println ("The notice has been issued");
System.out.println ("added" + (i + 1) + "Element!");
Thread.Sleep (1000);
A 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 (); }
}
}
The action is performed when thread a waits for a condition to be satisfied (List.size () ==5). Thread B adds the element to the list, changing the size of the list.
How does a,b communicate with each other? In other words, how does thread a know that list.size () is already 5?
Here we use the wait () and the Notify () method of the object class.
When the condition is not met (List.size ()!=5), thread A calls wait () to discard the CPU and enter the blocking state. ---does not consume CPU as ②while polling
When the condition is met, thread B calls the Notify () notification thread A, the so-called notification thread A, which wakes up thread A and lets it into a running state.
One advantage of this approach is that CPU utilization has increased.
But there are some drawbacks: for example, thread B executes first, adds 5 elements at a time and invokes notify () to send a notification, while thread A also executes, and when thread a executes and invokes wait (), it never wakes up. Because, thread B has been notified, and will not be notified later. This means that the notification is premature and disrupts the execution logic of the program.
The above in-depth understanding of the Java multi-line thread of communication between the threads is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud-dwelling community.