假设现在有这样的一个情况,生产者生产一个物品的同时要让消费者取走。
生产者要将自己生产的一个产品交到一个公共的区域(商城,超市),让消费者去取走(购买)。
所以这个时候我们要考虑到线程同步和线程重复取值的一个问题。
(同步--> synchronized,重复取值--->设定一个标记值,当达到条件时执行,未满足条件时等待)
class Messager{
private String name;
private String note;
private boolean flag = false;
public synchronized void set(String name,String note){
if(this.flag == true){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.note = note;
this.flag = true;
super.notify();
}
public synchronized void get(){
if(this.flag == false){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产的名称:"+this.name+"生产的内容:"+this.note);
this.flag = false;
super.notify();
}
}
class Producter implements Runnable{
private Messager msg;
public Producter(Messager msg){
this.msg = msg;
}
@Override
public void run() {
for(int i=0; i<10;i++){
if(i%2==0){
msg.set("物品A", "物品A制作完毕。");
}else{
msg.set("物品B","物品B制作完毕。");
}
}
}
}
class Consumer implements Runnable{
private Messager msg;
public Consumer(Messager msg){
this.msg = msg;
}
@Override
public void run() {
for (int x=0 ;x<10; x++){
msg.get();
}
}
}
public class Test{
public static void main(String args[]){
Messager msg = new Messager();
new Thread(new Producter(msg)).start();
new Thread(new Consumer(msg)).start();
}
}