JAVA 并发编程: 线程间的协作( wait / notify / sleep / yield / join )

转载 https://www.cnblogs.com/paddix/p/5381958.html

一、线程的状态

  New - 新建状态当线程创建完成时为新建状态, 即 new Thread(...),还没调用 start 方法时,线程处于新建状态

  Runnable - 就绪状态当调用线程的start 方法后,线程进入就绪状态,等待 CPU 资源。处于就绪状态的线程由Java 运行时系统的线程调度程序(thread scheduler) 来调度

  Running - 运行状态就绪状态的线程获取到 CPU 执行权以后进入运行状态,开始执行 run 方法。

  Blocked - 阻塞状态线程没有执行完,由于某种原因(如 , I/O 操作等) 会让出CPU 执行权,自身进入阻塞状态

  Dead - 死亡状态线程执行完成或者执行过程中出现异常,线程会进入死亡状态。

 

 

 二、 wait/nofity/notifyAll 方法等使用

  1、 wait 方法

  JDK 中一共提供了3个方法

  (1)wait() 方法的作用是将当前运行的线程挂起(即让其进入阻塞状态), 直到 notify 或 notifyAll 方法来唤醒线程

  (2)wait(long timeout) 该方法与wait() 方法类似,唯一的区别是在指定时间内,如果没有notify 或 notifyAll 方法的唤醒,也会自动唤醒

  (3)wait(long timeout, long nanos) 本意在于更精确的控制调度时间,不过从目前版本来看,该方法貌似没有完整的实现该功能(JDK1.8 源码如下)

  

复制代码
public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos > 0) {
            timeout++;
        }

        wait(timeout);
    }
复制代码

从源码来看,JDK8 中对纳秒的处理,是向上取整的,本质还是用的wait(long timeout) 的方法。

使用实例

复制代码
public class ThreadDemo extends Thread{

    public void run() {
        System.out.println("thread start ----");
        try {
            wait(2000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("thread end ----");
    }

    public static void main(String[] args) throws Exception{
        ThreadDemo threadDemo = new ThreadDemo();
        threadDemo.start();
    }
}
复制代码

 

 运行后结果报错, 这句话的意思是: 线程试图等待对象的监视器或者试图通知其他正在等待对象监视器的线程,但本身没有监视器的所有权。 wait 是一个本地方法,其底层是通过一个叫做监听器锁的对象来完成的。上面之所以抛出异常,是因为在调用 wait() 方法时没有获取到 monitor 对象的所有权,那如何获取 monitor 对象的所有权? java 中只能通过 synchronized 关键字来完成,修改后增加 Synchronized 关键字:

复制代码
public class ThreadDemo extends Thread{

    public void run() {
        synchronized (this) {
            System.out.println("thread start ----");
            try {
                wait(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("thread end ----");
        }
    }

    public static void main(String[] args) throws Exception{
        ThreadDemo threadDemo = new ThreadDemo();
        threadDemo.start();
    }
}
复制代码

 

 通过上述例子, 可知 wait 方法的使用必须在同步的范围内,否则就会抛出 IllegalMonitorStateException 异常,wait 方法的作用就是阻塞当前线程 等待 notify/notifyAll 方法的唤醒,或者等待超时后自动唤醒。

  2、 notify / notifyAll 方法

  既然 wait 方法时通过对象的monitor对象来实现的,所以只要在同一对象上去调用 notify/notifyAll 就可以唤醒对象monitor上等待的线程了。 notify/notifyAll 的区别在于前者只唤醒 monitor 上的一个线程,对其他线程没有影响,而 notifyAll 则唤醒所有线程,下面实例理解一下:

复制代码
public class ThreadDemo02{

   public synchronized void testWait() {
       System.out.println(Thread.currentThread().getName() + "thread start ---");
       try{
           wait();
       }catch (Exception e) {
            e.printStackTrace();
       }
       System.out.println(Thread.currentThread().getName() + "end -----");
   }

    public static void main(String[] args) throws Exception{

       ThreadDemo02 t = new ThreadDemo02();
       for(int i=0; i<5; i++ ){
           new Thread(new Runnable() {
               @Override
               public void run() {
                   t.testWait();
               }
           }).start();
       }

        synchronized (t) {
            t.notify();
        }
        Thread.sleep(3000);
        System.out.println("---------------分割线---------------");

        synchronized (t) {
            t.notifyAll();
        }
    }
}
复制代码

 

 从结果可以看出: 调用notify 方法时只有 Thread-0 被唤醒,但是调用 notifyAll 时,所有的线程都被唤醒了。

最后,有两点需要注意: (1) 调用 wait 方法后,线程是会释放对 monitor 对象的所有权的。

            (2)   一个通过 wait 方法阻塞的线程, 必须同时满足以下两个条件才能被真正执行

              a、线程需要被唤醒(超市唤醒或者调用notify/notifyAll)

              b、线程唤醒后需要竞争到锁(monitor)

 

三、 sleep / yield / join 方法解析

  上面我们已经清楚了 wait 和 notify 方法的使用和原理, 现在我们来看另一组线程间协作的方法。 这组方法跟上面方法最明显的区别是: 这几个方法位于 Thread 类中, 而上面三个方法都位于 Object 类中。 现在我们住个分析 sleep / yield / join 方法:

  1、 sleep

    sleep 方法的作用就是让当前线程暂停指定的时间(毫秒), sleep 方法是最简单的方法,在上述的例子中也用到过,比较容易理解。唯一需要注意的地方是与 wait 方法的区别。 最简单的区别就是 wati方法依赖于 同步, 而 sleep方法可以直接调用。 而更深层次的区别在于 sleep 方法只是暂时让出 CPU 的执行权,并不释放锁。而 wait方法需要释放锁。

复制代码
package com.bigdog.yyds.Service;

public class SleepDemo {

    public synchronized void sleepMethod() {
        System.out.println("Sleep start -----------");
        try{
            Thread.sleep(1000);
        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Sleep end -----------");
    }

    public synchronized void waitMethod() {
        System.out.println("Wait Start ---------");

        try{
            wait(1000);
        }catch (Exception e){
            e.printStackTrace();
        }

        System.out.println("Wait End ---------");
    }

    public static void main(String[] args) {
        SleepDemo test1 = new SleepDemo();

        for(int i=0; i<3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    test1.sleepMethod();
                }
            }).start();
        }

        try{
            Thread.sleep(10000);    //暂停10s,等待上面程序执行完成
        }catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("--------分割线--------------");

        SleepDemo test2 = new SleepDemo();

        for(int i=0;i<3;i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    test2.waitMethod();
                }
            }).start();
        }
    }
}
复制代码

 

    这个结果区别很明显,通过sleep方法实现的暂停,程序是顺序进入同步块的,只有当上一个线程执行完成的时候,下一个线程才能进入同步方法,sleep 暂停期间一直持有 monitor对象锁,其他线程是不能进入的。 而 wait 方法则不同,当调用 wait方法后,当前线程会释放所持有的 monitor 对象锁,因此,其他线程还可以进入到同步方法,线程被唤醒后,需要竞争所,获取到锁之后再继续执行。

2、yield

  yield 方法的作用是暂停当前线程,以便其他线程有机会执行,不过不能指定暂停的时间,并且也不能保证当前线程马上停止。 yield 方法只是将 Running 状态变为 Runnable 状态,下面我们来看一个例子:

复制代码
package com.bigdog.yyds.Service;

public class YieldDemo implements Runnable{

    @Override
    public void run() {
        try{
            Thread.sleep(100);
        }catch (Exception e) {
            e.printStackTrace();
        }
        for(int i=0;i<5;i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
            Thread.yield();
        }
    }

    public static void main(String[] args) {
        YieldDemo runn = new YieldDemo();
        Thread t1 = new Thread(runn, "FirstThread");
        Thread t2 = new Thread(runn, "SecondThread");

        t1.start();
        t2.start();
    }

}
复制代码

 

 这个例子就是通过 yield 方法来实现两个线程的交替执行。不过请注意:这种交替并不一定能得到保证,源码中对这个问题进行了说明

复制代码
/**
     * 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.
     *
     * <p> Yield is a heuristic attempt to improve relative progression
     * between threads that would otherwise over-utilise a CPU. Its use
     * should be combined with detailed profiling and benchmarking to
     * ensure that it actually has the desired effect.
     *
     * <p> It is rarely appropriate to use this method. It may be useful
     * for debugging or testing purposes, where it may help to reproduce
     * bugs due to race conditions. It may also be useful when designing
     * concurrency control constructs such as the ones in the
     * {@link java.util.concurrent.locks} package.
     */
复制代码

意思是:

    a、调度器可能会忽略该方法

    b、使用的时候要仔细分析和测试,确保能达到预期的效果

    c、 很少有场景用到该方法,主要适用的地方是调试和测试

3、join 方法

  join 方法的作用是父线程等待子线程执行完之后再执行,换句话说就是 将一部执行的线程合并为同步执行的线程。 JDK中提供了3个版本的方法, 实现与wait 方法类似, join() 方法实际执行的 join(0) , 而 join(long millis, int nanos) 也与 wait(long millis, int nanos) 实现方式一致,暂时对纳秒的支持也是不完整的。

复制代码
    public final void join() throws InterruptedException {
        join(0);
    }

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);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }
public final synchronized void join(long millis, int nanos)
    throws InterruptedException {

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        join(millis);
    }
复制代码

大家重点关注一下 join(long millis) 方法的实现,可以看出 join 方法就是通过 wait 方法来将线程的阻塞,如果 join 的线程还在执行,则将当前线程阻塞起来,直到 join的线程执行完成,当前线程才能执行。不过有一点需要注意,这里的join 只调用了wait方法,却没有对应的notify方法,原因是Thread 的 start 方法中做了相应的处理,所以当join 线程执行完成以后,会自动唤醒主线程继续往下执行,下面来看一个例子

(1) 不使用 join 方法

复制代码
package com.bigdog.yyds.Service;

public class JoinDemo implements Runnable{

    @Override
    public void run() {
        try{
            System.out.println(Thread.currentThread().getName() + "start =====");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "end =======");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        for(int i=0;i<5;i++) {
            Thread test = new Thread(new JoinDemo());
            test.start();
        }
        System.out.println("Finished ~~~~~");
    }
}
复制代码

(2) 使用 join 方法

复制代码
package com.bigdog.yyds.Service;

public class JoinDemo implements Runnable{

    @Override
    public void run() {
        try{
            System.out.println(Thread.currentThread().getName() + "start =====");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "end =======");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        for(int i=0;i<5;i++) {
            Thread test = new Thread(new JoinDemo());
            test.start();
            try{
                test.join();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println("Finished ~~~~~");
    }
}
复制代码

 

  对比两段代码的执行结果很容易发现,在没有使用 join 方法之前,线程是并发执行的,而使用 join 方法后,所有线程是顺序执行的。

四、总结

  本文主要详细讲解了 wait / notify/notifyAll 和 sleep/yield/join 方法。最后回答一下上面提出的问题:

wait/notify/notifyAll 方法的作用是实现线程间的协作,那为什么这3个方法不是 位于Thread类中,而是位于Object类中? 位于 Object 类中,也就相当于所有的类都包含这3个方法。要回答这个问题,还得回过头来看 wait 方法的实现原理,大家需要明白的是,wait等待的到底是什么东西?如上面的内容理解的比较好的话,大家很容易知道wait 等待的其实是对象 monitor,由于 Java 中每一个对象都有一个内置的monitor对象,自然所有的类都理应有 wait/notify 方法。

posted @   长弓射大狗  阅读(85)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示