java多线程三 wait sleep join yield

一,wait

是object类的方法,并不是线程的方法,使用此方法会使当前线程进入阻塞状态,过程中线程会释放cpu资源和锁资源,献策韩国你进入等待池,可以通过notify或者notifyall将线程唤醒,是线程重新进入就绪状态,在wait,notify和notifyall方法使用过程中一定要注意在同步方法或同步代码块中使用,因为在同步中才会获得锁,才能释放锁,java API强制规定,否则将报出java.lang.IllegalMonitorStateException异常。

二,sleep

sleep使Thread的方法,使强制使线程进入睡眠状态Thread.sleep(time)。在此过程中该线程只会释放掉cpu资源并不会释放锁资源,也就意味着目前对象实例的抢占到刚释放的cpu资源的线程不能获得同步资源锁,但是可以去抢占没有被占用的同步资源锁。

三,join

join方法的源代码

    /**
     * Waits for this thread to die.
     *
     * <p> An invocation of this method behaves in exactly the same
     * way as the invocation
     *
     * <blockquote>
     * {@linkplain #join(long) join}{@code (0)}
     * </blockquote>
     *
     * @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.
     */
    public final void join() throws InterruptedException {
        join(0);            //join()等同于join(0)
    }
    /**
     * Waits at most {@code millis} milliseconds for this thread to
     * die. A timeout of {@code 0} means to wait forever.
     *
     * <p> This implementation uses a loop of {@code this.wait} calls
     * conditioned on {@code this.isAlive}. As a thread terminates the
     * {@code this.notifyAll} method is invoked. It is recommended that
     * applications not use {@code wait}, {@code notify}, or
     * {@code notifyAll} on {@code Thread} instances.
     *
     * @param  millis
     *         the time to wait in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @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.
     */
    public final synchronized void join(long millis) throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;
 
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }
 
        if (millis == 0) {
            while (isAlive()) {
                wait(0);           //join(0)等同于wait(0),即wait无限时间直到被notify
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

可以看出join是一个同步方法,当主线程调用t的jion方法时会像去获得t的锁,然后主线程调用wait方法进入等待池,直到t线程运行结束main线程才能继续执行。

四,yield

线程让步,是将该线程,让出cpu资源进入可执行状态,然后与同优先级的线程再一并竞争抢占资源,也就是说并不意味着该线程一定会处于可执行状态,当其再一次抢到资源,会立即又转变成执行状态。

猜你喜欢

转载自blog.csdn.net/IPI715718/article/details/83713897