今天我们来详细讲一下关于wait、yield和sleep三种方法。
老规矩开讲之前我们先来了解几个概念。
J-1、InterruptedException 打断异常,关于这个异常我们先来看一下官方解释。大致的意思是这样的,当线程处于waiting、sleeping或者被占用被打断的时候,这个异常就会被抛出。可能会存在这种情况:你想用某个方法来测试当前的线程是不是被打断了的时候,线程会马上抛出这个异常。
/**
* Thrown when a thread is waiting, sleeping, or otherwise occupied,
* and the thread is interrupted, either before or during the activity.
* Occasionally a method may wish to test whether the current
* thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve
* this effect:
* <pre>
* if (Thread.interrupted()) // Clears interrupted status!
* throw new InterruptedException();
* </pre>
*
*/
本来想把interrupt的几个方法在这里总结一下,但是感觉跑题了,那就看另外一篇文章吧。Thread多线程Interrupt方法
1、线程Sleep
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds plus the specified
* number of nanoseconds, subject to the precision and accuracy of system
* timers and schedulers. The thread does not lose ownership of any
* monitors.
*
* @param millis
* the length of time to sleep in milliseconds
*
* @param nanos
* {@code 0-999999} additional nanoseconds to sleep
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative, or the value of
* {@code nanos} is not in the range {@code 0-999999}
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
private static void testSleep() {
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
Thread.currentThread().sleep(500);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
我们先来看下官方给出的解释,sleep()方法会导致当前正在执行的线程暂时性停止执行,睡眠的时间由方法的参数来规定。如果线程在睡眠前已经持有了线程锁,睡眠不会使线程释放锁。这个方法还可能会产生两种异常,一个是非法参数异常和打断异常。
2、线程yield
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use