多线程wait、yield、sleep、join详解

今天我们来详细讲一下关于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 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

echo.T

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值