Wait for notification mechanism
Preface: This series will start from the beginning of the Java multithreading related technology, the content of the "Java Multithreading Core technology" and "Java Concurrency Programming Practical" and other related information, hope to stand on the shoulders of giants, and then through my understanding can make knowledge more simple and understandable.
Directory
- Understanding CPUs, cores, and threads
- Java multithreaded Series (i) Java multithreading skills
- Concurrent access to object variables of the Java Multithreaded Series (ii)
- Java Multi-threaded series (three) of the waiting notification mechanism
- The use of Reentrantlock in Java Multithreading series (iv)
Non-pending notification
public void run() { try { for (int i = 0; i < 10; i++) { list.add(); System.out.println("添加了" + (i + 1) + "个元素"); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } }public void run() { try { while (true) { if (list.size() == 5) { System.out.println("==5了,线程b要退出了!"); throw new InterruptedException(); } } } catch (InterruptedException e) { e.printStackTrace(); } }
- Two threads implement communication, but when the list size is 5, thread B exits, but thread B keeps polling for 5, which is a resource.
- If the polling time interval is small, this time more waste of resources
- If the polling time interval is large, you may also miss the data you want, such as the possibility of missing 5
- Here to share the list, so the communication, but because do not know when to communicate, so constantly polling, this communication has shortcomings, one is a waste of CPU resources, the second is possible to read the wrong data
What is the wait notification mechanism
- Thread A waits for a notification from thread B to execute, and at this point thread A can execute the wait method, waiting for thread B to execute the Notify method to wake up thread A
Wait for notification mechanism implementation
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 void Run () {try {synchronized (lock) {for (int i = 0; i <; i++) {Mylist.add (); if (mylist.size () = = 5) {lock.notify (); SYSTEM.OUT.PRINTLN ("Notification has been issued! "); } System.out.println ("added" + (i + 1) + "Elements!"); Thread.Sleep (1000); }}} catch (Interruptedexception e) {e.printstacktrace (); } }
- Change the code above, when the size is not equal to 5, thread A is in the wait state until thread B notifies, wakes up thread A, waits for notification mechanism, avoids the resource waste caused by thread A's non-stop polling
Message notification mechanism attention point
- Wait and notify must be called in the synchronous method and in the synchronous code block, or the exception will be thrown
- The Notify method is inherited from the object class, which can wake up the thread that is waiting on this objects monitor, that is, the thread that wakes up the same lock
- After the Notify method is called, the lock is not released immediately, but the synchronization method is run or the code that runs the synchronization code block is run out
- A thread is randomly awakened after calling notify
- Locks are released after the wait method is called
- The interrupt thread throws an exception in the wait state
- Wait (long), which is automatically awakened after a set time, and can be woken up by another thread before the time has passed
- Notifyall all threads that can wake up the same lock
- If the thread is not in the waiting state and other threads wake up, it will not work and will disrupt the normal logic of the program.
Case: Producer Consumer Model A producer, a consumer
public void SetValue () {try {synchronized (lock) {if (! ValueObject.value.equals ("")) {lock.wait (); } String value = System.currenttimemillis () + "_" + system.nanotime (); System.out.println ("set" + value); Valueobject.value = value; Lock.notify (); }} catch (Interruptedexception e) {e.printstacktrace (); }}public void GetValue () {try {synchronized (lock) {if (ValueObject.value.equals (" ")) {lock.wait (); } System.out.println ("get" + valueobject.value); Valueobject.value = ""; Lock.notify (); }} catch (Interruptedexception e) {e.printstacktrace (); }}public void Run () {while (true) {r.getvalue (); }}public void Run () { while (true) {p.setvalue (); } }
- If we create a production line, a consumer thread, then this time it will run alternately
Multiple producers, multiple consumers
public void GetValue () {try {synchronized (lock) {while (ValueObject.value.equals ("")) {System.out.println ("consumer" + thread.currentthread (). GetName () + "waiting ☆ "); Lock.wait (); } System.out.println ("Consumer" + thread.currentthread (). GetName () + "runnable"); Valueobject.value = ""; Lock.notify (); }} catch (Interruptedexception e) {e.printstacktrace (); }}public void Run () {while (true) {r.getvalue (); }}public void SetValue () {try {synchronized (lock) {while (! ValueObject.value.equals ("")) {System.out.println ("producer" + THREAD.CURRENTTH Read (). GetName () + "waiting ★"); Lock.wait (); } System.out.println ("producer "+ Thread.CurrentThread (). GetName () +" runnable "); String value = System.currenttimemillis () + "_" + system.nanotime (); Valueobject.value = value; Lock.notify (); }} catch (Interruptedexception e) {e.printstacktrace (); }}public void Run () {while (true) {p.setvalue (); } }
- If this time to create multiple producers, multiple consumers, if the continuous wake Up is a similar thread, then there will be suspended animation state, that is, the thread is in the waiting state, because notify randomly wake up a thread, if the wake of the same kind, then wasted a wake, If you can't wake up a heterogeneous thread at this time, you'll be suspended. This situation changes the Notify to Notifyall () on the line.
The message notification mechanism needs to be noted where
- Whether the thread wakes up is the same thread that will cause the impact
- Producer consumption patterns, judging the conditions if and while should use which
Inter-thread communication through a pipeline
public class Threadwrite extends Thread {private WriteData write; Private PipedOutputStream out; Public Threadwrite (WriteData write, pipedoutputstream out) {super (); This.write = write; This.out = out; } @Override public void Run () {Write.writemethod (out); }}public class Threadread extends Thread {private readdata read; private PipedInputStream input; Public Threadread (ReadData read, PipedInputStream input) {super (); This.read = read; This.input = input; } @Override public void Run () {read.readmethod (input); }}public class Run {public static void main (string[] args) {try {writedata writedata = new Writeda Ta (); ReadData ReadData = new ReadData (); PipedInputStream InputStream = new PipedInputStream (); PipedOutputStream outputstream = new PipedOutputStream (); Inputstream.connect (OutputStream); OutputStream. connect (InputStream);//key Threadread Threadread = new Threadread (ReadData, InputStream); Threadread.start (); Thread.Sleep (2000); Threadwrite threadwrite = new Threadwrite (WriteData, OutputStream); Threadwrite.start (); } catch (IOException e) {e.printstacktrace (); } catch (Interruptedexception e) {e.printstacktrace (); } }}
- PipedInputStream and Piepedoutputstream (corresponding to the character stream Pipedreader and Pipedoutputwriter) These classes can implement inter-thread flow communication, connect the pipeline output stream and the output stream, Implement a thread to send data to a pipeline, a thread reads data from a pipe
Join method
public static void main(String[] args) { try { MyThread threadTest = new MyThread(); threadTest.start(); threadTest.join(); System.out.println("threadTest对象执行完,我再执行"); } catch (InterruptedException e) { e.printStackTrace(); } }
- The current thread is blocked (main thread), the calling thread (threadtest) executes normally, and when the front-end thread (main) resumes execution
public class ThreadB extends Thread { @Override public void run() { try { ThreadA a = new ThreadA(); a.start(); a.join(); System.out.println("线程B在run end处打印了"); } catch (InterruptedException e) { System.out.println("线程B在catch处打印了"); e.printStackTrace(); } }}
- If thread B finishes executing the Join method and thread B is interrupted at this time, then an exception is thrown, but thread a runs normally
The difference between join (long) and sleep (long)
public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }
- From the source of the Join method can be found, his core method is wait, mentioned in the previous wait method will release the lock, indicating that the Join method will also release the lock, but sleep will not release the lock.
- The Join method is non-static, while sleep is static
ThreadLocal
- To resolve the isolation of variables in each thread, and each thread binds its own value
public void Run () {try {for (int i = 0; i < i++) {if (Tools.tl.get ( ) = = null) {Tools.tl.set ("Threada" + (i + 1)); } else {System.out.println ("Threada get value=" + Tools.tl.get ()); } thread.sleep (200); }} catch (Interruptedexception e) {e.printstacktrace (); }}public void Run () {try {for (int i = 0; i <; i++) {if (Tools.tl.get () = = NULL) {Tools.tl.set ("threadb" + (i + 1)); } else {System.out.println ("threadb get value=" + Tools.tl.get ()); } thread.sleep (200); }} catch (Interruptedexception e) {e.printstacktrace (); }}public class Tools {public static ThreadLocal tl = new ThreadLocal ();}
- Each thread sets a value, but the resulting value is its own, isolated from each other
-
If you do not start without setting a value, the resulting value is NULL, you can set the initial value by inheriting threadlocal, overloading the Initalvalue method,
public class Threadlocalext extends ThreadLocal {@Overrideprotected Object initialvalue () {return new D
Ate (). GetTime ();}}
-
Inheritablethreadlocal, a child thread can inherit the value of the parent thread
public class Inheritablethreadlocalext extends inheritablethreadlocal {@Overrideprotected Object initialvalue () {return new Date (). GetTime ();}} public static void Main (string[] args) {try {for (int i = 0; i <; i++) {System.out.println (" Take the value = "+ Tools.tl.get ()) in the main thread; Thread.Sleep (100); } thread.sleep (5000); Threada a = new Threada (); A.start (); } catch (Interruptedexception e) {e.printstacktrace (); }}//main thread and a thread output
-
Override the Childvalue method to set the value of a child thread based on the above code
I think sharing is a kind of spirit, sharing is my pleasure, not to say I think I said must be right, I said may be a lot of wrong, but I hope I said something is my life experience and thinking, is to give a lot of people to reflect on, maybe give you a second, half a second, even if a word a little bit of truth, triggered their This is my greatest value. (This is my favorite word, but also I write the original intention of the blog)
Java multithreaded Series (iii)