ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

多线程-3.sleep() yield() join()

2021-03-12 15:01:17  阅读:179  来源: 互联网

标签:join Thread thread millis sleep 线程 多线程 方法


1.sleep()方法   jdk文档描述:Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.   当前正在执行的线程休眠(暂停执行)为指定的毫秒数,依赖系统定时器和调度的精度和准确性。线程不失去任何监视器的所有权。也就是说如果在syncronized同步代码块内执行该静态方法,其它线程不能获得该监视器,不能执行代码块。注意:该方法是Thread类静态方法。
1 // Thread.java 静态方法
2 public static native void sleep(long millis) throws InterruptedException;
2.yield()方法   jdk文档描述:A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.   给调度程序提示:当前线程将让出它正在使用的CPU处理器。调度程序可以选择忽略这个提示(可以让出,也可以不让出)。就是可能将当前线程转为就绪状态,让出CPU,也可能继续执行当前线程的程序。当前线程也不会失去监视器。
// Thread.java 静态方法
public static native void yield();
3.join()方法   jdk文档描述:Waits for this thread to die.   直接调用xx.join()方法,当前线程会一直执行while循环直至线程实例xx变成terminated结束状态。   当前线程进入join(0)方法前,会先获取thread对象的锁,并在方法里面等待直到线程终结,Thread对象在映射线程结束的时候自动调用notifyAll()方法唤醒所有等待的线程进入锁等待池,待当前线程获得锁后会执行后续代码然后退出join()方法。
 1 // Thread.java
 2 public final void join() throws InterruptedException {
 3     join(0);
 4 }
 5 /**
 6  * Waits at most {@code millis} milliseconds for this thread to
 7  * die. A timeout of {@code 0} means to wait forever.
 8  */
 9  // 因为函数内使用了wait()方法,必须用syncronized关键字修饰方法
10 public final synchronized void join(long millis)
11 throws InterruptedException {
12     long base = System.currentTimeMillis();
13     long now = 0;
14 
15     if (millis < 0) {
16         throw new IllegalArgumentException("timeout value is negative");
17     }
18     // 直到使用方法的线程实例变为terminated状态,当前线程(不是调用方法的线程实例,通常是其父线程)
19     // 都会一直执行循环代码
20     if (millis == 0) {
21         while (isAlive()) {
22             wait(0);
23         }
24     } else {
25         // 等待z至少millis毫秒后,当前线程跳出循环代码
26         while (isAlive()) {
27             long delay = millis - now;
28             if (delay <= 0) {
29                 break;
30             }
31             wait(delay);
32             now = System.currentTimeMillis() - base;
33         }
34     }
35 }

标签:join,Thread,thread,millis,sleep,线程,多线程,方法
来源: https://www.cnblogs.com/ningbing/p/14523937.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有