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

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()方法唤醒所有等待thread对象的线程进入锁等待池,待线程获得锁后会执行后续代码然后退出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 }

posted @ 2021-03-12 14:58  凝冰物语  阅读(82)  评论(0编辑  收藏  举报