wait & notify的错误理解
发布时间:2020-12-15 01:56:48 所属栏目:Java 来源:网络整理
导读:原本以为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
原本以为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 [email?protected] 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |