多线程间的通信:多个线程都在处理同一个资源,但是处理的任务不一样
等待唤醒机制。
生产者,消费者:
/*
需求:生产者每生产一个产品,消费者就消费一个。
通过同步,解决了没生产就消费的问题。
但是出现了连续的生产没有消费的情况,和需求生产一个,消费一个的情况不符
使用了等待唤醒机制.
wait():该方法可以让线程处于冻结状态,并且将线程临时存储到线程池中。
notify():唤醒指定线程池中的任意一个线程。
notifyAll():唤醒指定线程池中的所有一个线程。
这些方法必须使用在同步中,因为他们用来操作同步锁上的线程状态的。
在使用这些方法时,必须标示他们所属于的锁。标示方式就是 锁对象.wait()
锁对象.notify() 锁对象.notifyAll()
相同锁的notify(),可以获取相同锁的wait();
*/
public class ProducerConsumerDemo {
public static void main(String[] args) {
//1.创建资源
Res r = new Res();
//2.创建两个任务
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
//3.创建线程
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
//3.创建线程
t1.start();
t2.start();
}
}
//资源
class Res {
private String name;
private int count = 1;
//定义标记
private boolean flag;
public synchronized void set(String name) throws InterruptedException{
if(flag)//判断标记为true就执行wait等待,为false就生产
this.wait();
this.name = name + "--" + count;
count++;
System.out.println(Thread.currentThread().getName()+"..生产者..."+this.name);
//生产完毕将标记改为true
flag= true;
//唤醒消费者
this.notify();
}
public synchronized void get() throws InterruptedException{
if(!flag)
this.wait();
System.out.println(Thread.currentThread().getName()+"......消费者..."+this.name);
//将标记改为false
flag = false;
this.notify();
}
}
//生产者
class Producer implements Runnable{
private Res r ;
Producer(Res r){
this.r = r;
}
public void run(){
while(true){
try {
r.set("面包");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//消费者
class Consumer implements Runnable{
private Res r ;
Consumer(Res r){
this.r = r;
}
public void run(){
while(true){
try {
r.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
关注我的微信公众号(曲健磊的个人随笔),观看更多精彩内容: