wait & notify的错误理解

Posted lnas01

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了wait & notify的错误理解相关的知识,希望对你有一定的参考价值。

原本以为notify 可以直接唤醒处于wait状态的线程 实则不然

package waitNotify;

/** <p>
 *     Wait and notify in Java; low-level multithreading methods of the
 *  Object class that allow you to have one or more threads sleeping,
 *  only to be woken up by other threads at the right moment.
 *  Extremely useful for avoiding those processor-consuming polling loops.
 * </p>
 * 
 * <p>
 * The full tutorial and the majority of the code is available at
 * https://www.udemy.com/java-multithreading/?dtcode=KmfAU1g20Sjj#/
 * </p>
 * 
 * <p>
 * @author kanastasov L1087591@live.tees.ac.uk December-2014
 * </p>
 */
import java.util.Scanner;


public class Processor 

    public void produce() throws InterruptedException 
        synchronized (this) 
            System.out.println("Producer thread running ....");
            wait();
            System.out.println("Resumed.");
        
    

    public void consume() throws InterruptedException 
        
        Scanner scanner = new Scanner(System.in);
        Thread.sleep(2000);
        
        synchronized (this) 
            System.out.println("Waiting for return key.");
            scanner.nextLine();
            System.out.println("Return key pressed.");
            notify();
            Thread.sleep(5000); //notify后 produce线程不会马上苏醒 必须先执行沉睡命令 继而释放锁。 最终produce线程重新获取锁以后 才继续向下执行。
        
    

 

mygist copy from Carve ?

https://github.com/lnas01/MultithreadingJava/blob/master/8_WaitAndNotify/src/waitNotify/Processor.java

 

以上是关于wait & notify的错误理解的主要内容,如果未能解决你的问题,请参考以下文章

JUC并发编程 -- 为什么需要wait/notify方法 & 原理之 wait / notify & wait() 和 notify() API介绍

[Java复习05] 多线程&并发 知识点补充

Java Object对象中的wait,notify,notifyAll的理解

Java并发编程原理与实战二十一:线程通信wait&notify&join

wait(),notify(),notifyAll()的理解与使用

转载Java - Wait & Notify