解决数据的重复设置或重复取出,需要等待及唤醒机制
public final void wait ()throws InterruptException;死等
public final void wait(long timeout) throws InterruptedException; 活等
public final void notify();
唤醒第一个
public final void notifyAll();
唤醒所有
package com.pra.synchronizedcase.union;
class Data{
private String title;
private String note;
//flag=true 表示允许生产,但是不允许消费者取走
//flag=flase 表示不允许生产,但允许消费者取走
private boolean flag = true;
public synchronized void get() {
if(flag==true){
//已经生产了,不允许重复生产
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.title+"="+this.note);
flag=false;
super.notify();
}
public void set(String title,String note) {
this.title = title;
if(flag==false){
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
flag=true;
super.notify();
this.note = note;
}
}
请解释sleep()与wait()的区别
sleep()是Thread类中定义的方法,到了一定的时间可以自动唤醒
wait()是Object类中定义的方法,如果要想唤醒,必须使用notify()或者notifyAll()方法