Layout: Post title: “Wait and notify” subtitle: “Object.wait()/notify()”” date: 2018-10-07 08:00:00 author: “Header-img” : “img/ post-BG-2015.jpg “catalog: true tags: – Multi Thread
preface
How do threads communicate with each other? Threads share data, so naturally they can communicate with each other. And the main problem that multithreading needs to solve is how to ensure multithreading access to shared data.
How to communicate? One such approach and application scenario is to use Wait /notify to control the order in which threads execute and access shared data.
Note: The JDK also does not recommend using Wait /notify!
1. Each object has a monitor. 2. Each object also has a collection of wait threads. Thread collections can only be operated by locking objects. Wait /notify.
How do processes communicate? 1. Sockets 2. Messaging middleware 3. Remote services
2 different procedures, you can achieve data interchange!
role
Can thread communication problems. Thread communication needs to handle synchronization. How? The two methods are as follows: 1. Wait /notify 2
How to use
1. The current thread must acquire/own the lock object. To invoke wait/notify on the lock object, the thread must acquire the lock object first.
Before a thread object calls wait/notify of the lock object, it must ensure that the current thread owns the lock object. As a result, wait/notify of the lock object must be called in the synchronized code block. Because the current thread owns the lock object and can only call wait/notify of the lock object if the lock object is called in the synchronized code block.
2. Lock object and lock object Wait /notify must be the same object. Otherwise, an error will be reported. – Invalid monitor status is abnormal.
Lock objects in wait/notify must be in synchronized blocks/methods because lock objects/monitors and lock objects in wait/notify must be the same object. That’s in 2.
/ / callwaitSynchronized (obj) {// The current thread must acquire the lock objectwhile(<condition does not hold>) obj.wait(timeout); / / callwaitThe notify object and the lock object are the same object // callwaitThe /notify code must be in the sync code block... // Perform action appropriate to condition} // notify synchronized {// Write thread: write shared data object. NotifyAll (); // Activate the reader thread}Copy the code
Wait method
Wait () is the same as wait(0).
The argument is 0, indicating infinite waiting, that is, waiting until notified by another thread.
What is the difference between wait and sleep, yield?
The common denominator is to stop the current thread.
Wait // Thread A waives the lock. When will it resume? 1. Before the specified time expires, another thread B calls notify after modifying data and completing the task. Thread A obtains the lock again and executes the task again. 2. No other thread calls notify. When the time is up, thread A continues to obtain the lock and execute the notify.
Sleep // Thread A does not abandon the lock. Yield is also the same, it just gives up the CPU. Sleep and yield are the same in terms of whether to abandon the lock, neither of which abandon the lock, but only the CPU.
The stop time of sleep is fixed, that is, the time specified by the parameter. When will it resume? Resume when the time is up.
Yield’s stop time is indeterminate; it simply gives up the CPU and takes another thread of the same priority from the set of threads waiting to execute. Or maybe it’s me again. When will it resume? The timing is uncertain and depends on the CPU and thread scheduler.
Javarevisited.blogspot.com/2011/12/dif… www.jianshu.com/p/25e959037…
The difference between wait and join
Join — “this.wait –” Lock object is used by thread object. Let the current main thread wait until the object lock thread 1(referring to thread 1.join()) completes execution. Thread 2 is then started. This ensures that thread 1 and thread 2 are executed in sequence.
www.importnew.com/14958.html www.java67.com/2017/11/dif…
What does it mean when the thread is finished?
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()) {// The object locks thread 1 and then thread 2 -- how does this work? Thread 1 completes execution, the thread dies, the loop ends, thread 1.join() completes execution, and continues execution of the main thread, starting thread 2. // The problem is that the main thread is waiting on the lock of thread 1, and it is waiting wirelessly. Unless another thread calls thread 1.notify(), the main thread should still wait. The thread died and the join() method finished, which is understandable -- but why did thread 1 die, join() finish, and why did the main thread restart? How can the main thread come to life without another thread calling thread 1.notify()? That is, when thread 1 exitsexitNotifyAll () when (). HTTP: / / https://juejin.cn/post/6844903624842149895 / / there is a problem, and the onewaitWon't () do it? Why loop? Because calling once is still making the main thread wait, and calling n times is still making the main thread wait, so what does the loop do? To prevent false wakeup, see api-object.wait (). As for what false awakening is, you need to look at Wikipedia again.wait(0); }}else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay); now = System.currentTimeMillis() - base; }}}Copy the code
Juejin. Cn/post / 684490…
Docs.oracle.com/javase/7/do…
Analysis of various scenarios of thread communication
Wingjay.com/2017/04/09/…
Job application
Many services are not Web applications, but Java applications. How do I start them? The main method starts, of course. But the program can’t be shut down once it’s started. It’s always providing service. How to do? While (true) cycle.
Based on the while(true) loop, the main thread should also be made to wait, so as not to shut down the program, but to provide services to the outside. Most importantly, the program should be made to wait, so as not to consume and occupy the resources of the computer by executing unnecessary code through the loop. Do not let the CPU execute the code in while(true) because it is pure waste.
code
package gzh.spring;
/* */ import java.text.SimpleDateFormat;
/* */ import java.util.Date;
/* */ import org.apache.commons.logging.Log;
/* */ import org.apache.commons.logging.LogFactory;
/* */
/* */
/* */ public class Main
/* */ {
/* 12 */ private static Log log = LogFactory.getLog(Main.class);
/* */
/* 14 */ private static volatile boolean running = true;
/* */
/* */ public static void main(String[] args) {
/* 17 */ Runtime.getRuntime().addShutdownHook(new Thread() {
/* */ public void run() {
/* */ try {
/* 20 */ AppContext.stop();
/* 21 */ Main.log.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " Main server stopped!");
/* */ } catch (Throwable t) {
/* 23 */ Main.log.error("Main stop error:" + t);
/* */ }
/* 25 */ synchronized (Main.class) {
///* 26 */ Main.accessThe $102(false); /* 27 */ Main.class.notify(); /* */} /* */} /* */}); /* */ try /* */ { /* 33 */ AppContext.start(); /* */ } catch (RuntimeException e) { /* 35 */ log.error(e.getMessage(), e); /* 36 */ throw e; /* */ } /* */ /* 39 */ log.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " Main server started!");
/* */
/* 41 */ synchronized (Main.class) {
/* 42 */ while(running) { /* */ try { /* 44 */ Main.class.wait(); // let the main threadwait
/* */ }
/* */ catch (Throwable e) {}
/* */ }
/* */ }
/* */ }
/* */ }
Copy the code
reference
www.cnblogs.com/stateis0/p/…
Docs.oracle.com/javase/tuto…
www.kancloud.cn/digest/java…