Home >Java >javaTutorial >What are the four commonly used thread functions in Java?
Causes the current thread to wait until it is awakened, usually by being notified or interrupted, or until a certain real-time time has elapsed.
itself belongs to an Object class. You can see from the source code: public class Object {
Looking at the source code, you can see that there are three overloaded methods. The detailed source code is as follows:
//第一个重载函数 public final void wait() throws InterruptedException { wait(0L); } //第二个重载函数 public final native void wait(long timeoutMillis) throws InterruptedException; //第三个重载函数 public final void wait(long timeoutMillis, int nanos) throws InterruptedException { if (timeoutMillis < 0) { throw new IllegalArgumentException("timeoutMillis value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos > 0 && timeoutMillis < Long.MAX_VALUE) { timeoutMillis++; } wait(timeoutMillis); }
The specific actual calling code is as follows:
If the wait function is executed, within these 4 seconds, the lock will be released and the thread will be suspended. If you cooperate with notify() within these four seconds, you can wake up and get the lock. If you don't wake up, wait for others to compete. After 4 seconds, the lock will be automatically released by default
While the current thread is waiting for Thread.wait(), if Thread ends, it can automatically wake up and automatically release the lock
@Override public void run() { synchronized (a) { a.wait(4000); } }
join is a method of Thread class
View its source code. The specific source code is as follows. The three overloaded methods
//第一个重载函数 public final synchronized void join(final long millis) throws InterruptedException { if (millis > 0) { if (isAlive()) { final long startTime = System.nanoTime(); long delay = millis; do { wait(delay); } while (isAlive() && (delay = millis - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0); } } else if (millis == 0) { while (isAlive()) { wait(0); } } else { throw new IllegalArgumentException("timeout value is negative"); } } //第二个重载函数 /*等待该线程死亡的时间最多为毫秒加纳秒。 如果两个参数都为0,则意味着永远等待。 这个实现使用了This的循环。 等待电话以this.isAlive为条件。 当一个线程终止this。 调用notifyAll方法。 建议应用程序不要使用wait、notify或notifyAll on Thread实例。 */ public final synchronized void join(long millis, int nanos) throws InterruptedException { if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos > 0 && millis < Long.MAX_VALUE) { millis++; } join(millis); } //第三个重载函数 /*等待线程死亡。 此方法的调用与调用的行为完全相同 InterruptedException—如果任何线程中断了当前线程。 当抛出此异常时,当前线程的中断状态将被清除。 */ public final void join() throws InterruptedException { join(0); }
The main time parameter logic is as follows:
is less than 0, an exception is thrown.
is equal to 0, join(A), determines whether A exists, and performs the operation only if it exists. This thread executes wait(0) and waits for thread A to finish executing.
is greater than 0, the same as above, except that it executes wait(long millis). After the waiting time is over, Before you can continue to perform the operation
Compare the previous wait function
sleep(long mills) : Give up CPU resources, but will not release lock resources.
wait(): Give up CPU resources and lock resources.
Looking at the source code of the sleep function, there are two overloaded functions
Both are functions of the Thread class
/*根据系统计时器和调度器的精度和准确性, 使当前执行的线程在指定的毫秒数内处于睡眠状态(暂时停止执行)。 线程不会失去任何监视器的所有权。*/ public static native void sleep(long millis) throws InterruptedException; /*导致当前执行的线程在指定的毫秒数加上指定的纳秒数 (取决于系统计时器和调度器的精度和准确性)内休眠(暂时停止执行)。 线程不会失去任何监视器的所有权。 */ public static void sleep(long millis, int nanos) throws InterruptedException { if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos > 0 && millis < Long.MAX_VALUE) { millis++; } sleep(millis); }
Look at the source code of the yield() function. An overloaded function
is a function of the Thread class.
indicates to the scheduler that the current thread is willing to give up its current use of the processor. The scheduler can ignore this prompt.
Yield is a heuristic attempt to improve relative processes between threads that would otherwise overuse the CPU. Its use should be coupled with detailed analysis and benchmarking to ensure that it actually has the intended effect.
Using this method is rarely appropriate. It may be used for debugging or testing purposes where it may help to reproduce errors due to race conditions. It may also be useful when designing concurrency control constructs such as those in the java.util.concurrent.locks package.
public static native void yield();
In general, the main functions of the yield function are:
Give up CPU scheduling and pause threads, but the time cannot be specified by the user
Only the same priority can be given Level has execution opportunity
wait pauses the thread, gives up the CPU, and releases the lock. (Object class)
join pauses the thread and can return to its own thread after executing the thread. (Thread class)
sleep Pauses the thread and gives up the CPU without releasing the lock. (Thread class)
yield pauses the thread, but it cannot be specified by the user. It can only give the same priority the opportunity to execute. (Thread class)
After reading the above source code and logic code, let’s talk about the similarities and differences between the two
In general
wait function: Let the current thread enter the waiting state. wait() will be used together with notify() and notifyAll() methods. notify is the wake-up function
#join function: wait for this thread to end before executing your own thread. Its main function is to synchronize, changing the execution between threads from "parallel" to "serial". When the join() method of thread B is called in thread A, the execution process of thread
changes: thread A must wait for thread B to complete execution before it can continue execution
Common points:
Pause the current thread
can be woken up by interrupt
The difference is:
Difference | wait | join |
---|---|---|
Class | Object class | Thread class |
Purpose | Inter-thread communication | Sorting, let it pass serially |
Synchronization | must be synchronized | can be used without synchronized |
The above is the detailed content of What are the four commonly used thread functions in Java?. For more information, please follow other related articles on the PHP Chinese website!