//多线程中通信.多个线程都在处于同一资源,但是处理的任务却不一样
//生产者,生产一个面包
//消费者,消费一个面包.
class Res {
private int count = 1;// 面包数量
private String name;
boolean flag;// 定义标记
// 提供了商品的赋值的方法
public synchronized void set(String name){
// 判断标记 true 执行wait.等待,为false.就生产
if(flag){
try {
wait();
} catch (InterruptedException e) {
}
}
this.name = name+"----"+count;
count++;
System.out.println(Thread.currentThread().getName()+"--生产者----"+this.name);
// 生产完毕,将标记改为true
flag = true;
// 唤醒消费者
this.notify();
}
// 提供了商品获取的方法
public synchronized void get(){
if(!flag){
try {
wait();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName()+"---消费者---"+this.name);
// 将标记改为false
flag = false;
// 唤醒提供者
this.notify();
}
}
/**
* 消费者
*/
class Customer implements Runnable {
private Res r;
Customer(Res r){
this.r = r;
}
public void run(){
while (true) {
r.get();
}
}
}
/**
* 生产者
*/
class producer implements Runnable {
private Res r;
producer(Res r){
this.r = r;
}
public void run(){
while (true) {
r.set("面包");
}
}
}
public class WaitAndNotifyDemo {
public static void main(String[] args) {
// 1.创建线程资源
Res r = new Res();
// 2.创建线程任务
producer p = new producer(r);
Customer c = new Customer(r);
// 3.执行线程
new Thread(p).start();
new Thread(c).start();
}
}