import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Myth {
public static void main(String[] args){
Hanbao hanbao =new Hanbao();
HouChu houChu= new HouChu(hanbao);
Person person=new Person(hanbao);
Thread t1=new Thread(houChu);
Thread t2=new Thread(houChu);
Thread t3=new Thread(person);
Thread t4=new Thread(person);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Hanbao{
private int count=1;
public boolean flag=true;
public void shengchan() throws InterruptedException {
while (flag){ //使用while循环判断
try {
wait(); //会原地唤醒->如果使用if判断会原地唤醒继续执行下一行
System.out.print("xxx");不会进行二次判断->更改为while判断->原地唤醒也没问题
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(Thread.currentThread().getName()+"++++++++"+"生产汉堡"+(++count));
flag=true;
notifyAll();
}
public void xiaofei() throws InterruptedException {
while (!flag) {
try {
sLock.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(Thread.currentThread().getName()+"+++"+"卖出汉堡"+(--count));
flag = false;
notifyAll()
}
}
class HouChu implements Runnable{
private final Hanbao hanbao;
public HouChu(Hanbao hanbao){
this.hanbao=hanbao;
}
@Override
public void run() {
while (true){
try {
hanbao.shengchan();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class Person implements Runnable {
private Hanbao hanbao;
public Person(Hanbao hanbao) {
this.hanbao = hanbao;
}
@Override
public void run() {
while (true) {
try {
hanbao.xiaofei();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public final void wait() throws InterruptedException
导致当前线程等待,直到另一个线程调用该对象的notify()方法或notifyAll()方法。 换句话说,这个方法的行为就好像简单地执行呼叫wait(0) 。
当前的线程必须拥有该对象的显示器。 该线程释放此监视器的所有权,并等待另一个线程通知等待该对象监视器的线程通过调用notify方法或notifyAll方法notifyAll 。 然后线程等待,直到它可以重新获得监视器的所有权并恢复执行。
对于某一个参数版本中,中断和虚假唤醒是可能的,并且该方法应该始终在循环中使用:
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}