Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common functions of the four threads of Java

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces what the common functions of the four threads of Java are, which can be used for reference by interested friends. I hope you can learn a lot after reading this article.

1. Wait ()

Make the current thread wait until it is awakened, usually by being notified or interrupted, or until a certain amount of real-time time has elapsed.

It belongs to an Object class. If you look at the source code, you can see: public class Object {

If you look at the source code, you can see that there are three overloaded methods. The source code is as follows:

/ / the first overloaded function public final void wait () throws InterruptedException {wait (0L);} / the second overloaded function public final native void wait (long timeoutMillis) throws InterruptedException;// the third overloaded function 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); } 具体实战调用代码如下: 如果执行到了wait函数,在这4秒内,会释放锁,并且暂停线程。如果这四秒内配合notify()可以唤醒并且得到锁,如果没有唤醒,等待其他来竞争。4秒结束后,会默认自动释放锁 当前线程在 Thread.wait()等待过程中,如果Thread结束了,是可以自动唤醒的而且自动释放锁 @Overridepublic void run() { synchronized (a) { a.wait(4000); }}2. join() join是Thread类的方法 查看其源码,具体源码如下,三个重载的方法 //第一个重载函数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");} / / the second overloaded function / * waits for the thread to die in milliseconds and Ghana seconds at most. If both parameters are 0, it means waiting forever. This implementation uses This loops. Waiting for a call is conditional on this.isAlive. When a thread terminates this. Call the notifyAll method. It is recommended that applications do not use wait, notify, or notifyAll on Thread instances. * / 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); } 主要的时间参数逻辑如下: 小于0,抛出异常 等于0,join(A),判断A是否存在,存在才执行操作。该线程执行wait(0)等待,等待A线程执行完后才可结束 大于0,同上,只不过执行的是wait(long millis),等待时间结束后才可继续执行操作 3. sleep() 对比上一个wait函数 sleep(long mills):让出CPU资源,但是不会释放锁资源。 wait():让出CPU资源和锁资源。 查看sleep函数的源码,一共有两个重载函数 都是Thread类的函数 /*根据系统计时器和调度器的精度和准确性,使当前执行的线程在指定的毫秒数内处于睡眠状态(暂时停止执行)。 线程不会失去任何监视器的所有权。*/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);} 4. Yield ()

View the source code of the yield () function, an overloaded function

Are all functions of the Thread class

Hints to the scheduler that the current thread is willing to give up the current use of the processor. The scheduler can ignore this prompt.

Yield is a heuristic attempt to improve the relative processes between threads, otherwise you will overuse CPU. Its use should be combined with detailed analysis and benchmarking to ensure that it actually has the desired effect.

It is rarely appropriate to use this method. It may be used for debugging or testing purposes, where it may help to regenerate errors due to competitive conditions. It can also be useful when designing concurrency control constructs, such as those in the java.util.concurrent.locks package.

Public static native void yield ()

Generally speaking, the main functions of the yield function are:

Let CPU schedule and suspend the thread, but the time cannot be specified by the user

Can only give the same priority the opportunity to execute.

5. Summary

Wait pauses the thread, gives up cpu, and releases the lock. (Object class)

Join pauses the thread and executes it before returning to its own thread to run. (Thread class)

Sleep pauses the thread to give up the cpu without releasing the lock. (Thread class)

Yield pauses the thread, but it cannot be determined by the user and can only be executed at the same priority. (Thread class)

5.1 differences between wait and join

After looking at the above source code and logic code, let's talk about the similarities and differences between the two.

Generally speaking

The wait function: puts the current thread into a waiting state, and wait () is used with the notify () and notifyAll () methods. Notify is a wake-up function

Join function: a thread that waits for this thread to finish before it can execute itself. It mainly plays the role of synchronization, changing the execution between threads from "parallel" to "serial". When thread A calls the join () method of thread B, the thread

The execution process has changed: thread A must wait for thread B to finish execution before it can continue.

What they have in common:

Pause the current thread

Can be awakened by interruptions.

The differences are as follows:

Distinguish the communication sort between waitjoin class Object class Thread class destination threads, make it serial through synchronization must be synchronized can not use the difference between synchronized5.2 wait and sleep

Wait (): give up CPU resources and lock resources.

Sleep (long mills): gives up the CPU resource, but does not release the lock resource.

Look at the difference, mainly look at the operating mechanism of CPU:

The difference between them mainly considers two points: whether the 1.cpu will continue to execute, and 2. Whether the lock is released.

In the final analysis:

Wait,notify,notifyall are methods of Object objects that are used together for the locking mechanism, so the lock is released.

Sleep is a Thread class, which has nothing to do with the lock and does not release the lock.

But both will give up cpu resources.

Thank you for reading this article carefully. I hope the article "what are the common functions of the four threads of Java" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report