join
Thread. join Adds the specified thread to the current thread. It is possible to merge two alternating threads into sequential threads. For example, if thread B calls thread A’s Join() method, thread B will not continue executing until thread A finishes executing.
Public class JoinTest{public static void main(String[] args){try {// Create ThreadA t1 = new ThreadA("t1"); // Start "thread t1" t1.start(); // add "thread t1" to "main" and "main() will wait for it to complete" t1.join(); System.out.printf("%s finish\n", Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class ThreadA extends Thread{
public ThreadA(String name){
super(name);
}
public void run(){
System.out.printf("%s start\n", this.getName()); // Delay operationfor(int i=0; i <1000000; i++)
;
System.out.printf("%s finish\n", this.getName()); }}}Copy the code
The Join method is implemented via wait (hint: Object provides this method). When the main thread calls t. jin, the main thread acquires the lock on t and calls its wait until the object wakes up, for example after exiting. This means that when the main thread calls t.jin, it must be able to get the lock on the thread t object
yield
The thread.yield () method suspends the currently executing Thread object and executes another Thread.
Conclusion: Yield () never causes a thread to go to a wait/sleep/block state. In most cases, yield() causes the thread to go from the running state to the runnable state, but it may not.
conclusion
-
Sleep () blocks the thread for a certain amount of time, depriving it of CPU time, but does not release locked resources. When the specified time expires, the thread reenters the executable state
-
Wait () blocks a thread and releases any lock resources it holds. This is used with notify()
-
Suspend () puts a thread into a blocked state and does not automatically resume. Its corresponding resume() must be called before the thread can be put back into an executable state
The difference between:
-
Yield () causes a thread to give up its current allocation of CPU time, but does not block, meaning that the thread is still in an executable state and could be allocated CPU time again at any time.
-
Sleep (),suspend(),rusume(),yield() are all methods of Thread class, and wait() is methods of Object class
Refer to the article
- Java Multithreading — Join ()
- Thread.join() source code analysis
- Java multi-threaded join method understanding
- A method that causes a thread to enter a blocking state