java基础-多线程-wait、notify、notifyAll方法的使用

愿历尽千帆,归来仍是少年

wait:

  作用:当前运行线程挂起(阻塞),直到notify或notifyAll方法唤醒线程。

  注意:java.lang.IllegalMonitorStateExceptio,wait方法的使用必须在同步(synchronized)的范围内

  

    @ApiOperation(value = "basic线程测试-wait", notes = "basic线程测试-wait")
    @GetMapping(value = "/startWaitThread")
    public Response startWaitThread(){
        // Thread类
        // 新状态
        BasicWaitThread t1 = new BasicWaitThread("Thread-A");
        // 可运行状态
        t1.start();

        return Response.ok();
    }

 

/**
 * wait
 *
 * @author hxx
 * @version 1.0
 * @date 2021/7/13 16:30
 */
public class BasicWaitThread extends Thread {

    public static Logger logger = LogManager.getLogger(BasicWaitThread.class);


    public BasicWaitThread (String param) {
        super(param);
    }

    @Override
    public synchronized void run() {
        logger.info("start-----------"+Thread.currentThread().getName());
        try {
            wait(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("end-----------"+Thread.currentThread().getName());
    }
}

notify/notifyAll:唤醒monitor上等待的线程。

  notify:只能唤醒monitor上的一个线程,对其他线程没有影响。

  notifyAll:唤醒所有的线程。

 

  

    @ApiOperation(value = "basic线程测试-notify", notes = "basic线程测试-notify")
    @GetMapping(value = "/startNotifyThread")
    public Response startNotifyThread() throws InterruptedException {
        // Thread类
        // 新状态
        BasicNotifyThread basicNotifyThread = new BasicNotifyThread();
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    basicNotifyThread.testNotify();
                }
            }).start();
        }


        synchronized (basicNotifyThread) {
            basicNotifyThread.notify();
        }
        Thread.sleep(3000);
        synchronized (basicNotifyThread) {
            basicNotifyThread.notifyAll();
        }

        return Response.ok();
    }
/**
 * notify
 *
 * @author hxx
 * @version 1.0
 * @date 2021/7/13 16:30
 */
public class BasicNotifyThread {

    public static Logger logger = LogManager.getLogger(BasicNotifyThread.class);

    public synchronized void testNotify() {
        System.out.println(Thread.currentThread().getName() +" Start-----");
        try {
            wait(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() +" End-------");
    }
}

 

posted @ 2021-07-13 18:02  归来仍是少年-youg  阅读(174)  评论(0)    收藏  举报