首页 > 代码库 > java多线程 生产者消费者案例-虚假唤醒
java多线程 生产者消费者案例-虚假唤醒
package com.java.juc; public class TestProductAndConsumer { public static void main(String[] args) { Clerk clerk = new Clerk(); Produce produce = new Produce(clerk); Consumer consumer = new Consumer(clerk); new Thread(produce, "线程A").start(); new Thread(consumer, "线程B").start(); new Thread(produce, "线程AA").start(); new Thread(consumer, "线程BB").start(); } } // 店员 class Clerk { private int product = 0; public synchronized void get() { while (product >= 1) { //这里使用while 不使用if 防止虚假唤醒 System.out.println("产品已满!"); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " : " + ++product); this.notifyAll(); } public synchronized void sale() { while (product <= 0) { System.out.println("缺货!"); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " : " + --product); this.notifyAll(); } } // 生产者 class Produce implements Runnable { private Clerk clerk; public Produce(Clerk clerk) { this.clerk = clerk; } @Override public void run() { for (int i = 0; i < 20; i++) { try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } clerk.get(); } } } // 消费者 class Consumer implements Runnable { private Clerk clerk; public Consumer(Clerk clerk) { this.clerk = clerk; } @Override public void run() { for (int i = 0; i < 20; i++) { clerk.sale(); } } }
-
public final void wait() throws InterruptedException
Causes the current thread to wait until another thread invokes thenotify()
method or thenotifyAll()
method for this object. In other words, this method behaves exactly as if it simply performs the callwait(0)
.The current thread must own this object‘s monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object‘s monitor to wake up either through a call to the
notify
method or thenotifyAll
method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
synchronized (obj) { while (<condition does not hold>) //为了防止虚假唤醒应该总是使用在循环中 obj.wait(); ... // Perform action appropriate to condition }
This method should only be called by a thread that is the owner of this object‘s monitor. See thenotify
method for a description of the ways in which a thread can become the owner of a monitor.
java多线程 生产者消费者案例-虚假唤醒
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。