码迷,mamicode.com
首页 > 其他好文 > 详细

wait & notify的错误理解

时间:2019-07-24 19:21:37      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:running   唤醒   oop   live   scan   sys   ber   syn   evel   

原本以为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的错误理解

标签:running   唤醒   oop   live   scan   sys   ber   syn   evel   

原文地址:https://www.cnblogs.com/lnas01/p/11240199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!