共享内存中的两个同步方法,及同步方法中wait()方法的调用。html
执行wait后,当前线程处于等待状态,而且会释放锁。 执行notify后,当前线程并不会立刻释放锁,而是执行完runnable代码后才会释放锁。java
Java中有一个同步模型-监视器,负责管理线程对对象中的同步方法的访问,它的原理是:赋予该对象惟一一把'钥匙',当多个线程进入对象,只有取得该对象钥匙的线程才能够访问同步方法,其它线程在该对象中等待,直到该线程用wait()方法放弃这把钥匙,其它等待的线程抢占该钥匙,抢占到钥匙的线程后才可得以执行,而没有取得钥匙的线程仍被阻塞在该对象中等待。 总而言之,synchonized使得只有一个线程能进入临界代码区。bash
因为wait( )所等待的对象必须先锁住,所以,它只能用在同步化程序段或者同步化方法内,不然,会抛出异常java.lang.IllegalMonitorStateException.多线程
/**
* 仓库类,用于管理产品的生产、消费和存储。
*/
public class Storage<T> {
private int index = 0;
private static final int MAX = 10;//最大容量
private List<T> storages = new ArrayList<T>(MAX);//存储集合
public synchronized void produce(T item) {
while (index >= MAX) {// 判断仓库满了,则等待。
try {
System.out.println("仓库满了,等待中...");
this.wait();
System.out.println("仓库不满了,开始生产");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("生产>>" + item.toString());
storages.add(item);
index++; //先添加item,在进行加1操做
notify(); //唤醒在此对象监视器上等待的单个线程,即消费者线程
}
public synchronized T consume() {
while (index <= 0) {// 判断仓库满了,则等待。
try {
System.out.println("仓库为空,等待中...");
this.wait();
System.out.println("仓库不为空,开始消费");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;//先进行减1操做,再remove
T item = storages.remove(index);
System.out.println("消费>>" + item.toString());
notify();
return item;
}
}
复制代码
public class Phone {
private int id;// 手机编号
public Phone(int id) {
this.id = id;
}
@Override
public String toString() {
return "手机编号:" + id;
}
}
复制代码
public class Producer implements Runnable {
private Storage<Phone> storage;
public Producer(Storage<Phone> storage) {
this.storage = storage;
}
public void run() {
for(int i = 0;i<20;i++){
storage.produce(new Phone(i));
try {
Thread.sleep(10);//每隔10毫秒生产一个产品
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
复制代码
public class Consumer implements Runnable {
private Storage<Phone> storage;
public Consumer(Storage<Phone> storage) {
this.storage = storage;
}
public void run() {
for(int i = 0;i<20;i++){
storage.consume();
try {
Thread.sleep(100);//每隔100毫秒消费一个
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
复制代码
public class ProducerAndConsumer {
public static void main(String[] args) {
Storage<Phone> storage = new Storage<Phone>();
new Thread(new Producer(storage)).start();
new Thread(new Consumer(storage)).start();
}
}
复制代码
2018.11.18补充 如上代码知识模拟的一个生产者一个消费者的场景,并且生产者和消费者分别执行20次。彻底可使用while(true)使得一直生产和消费。 对于一个生产者和一个消费者的场景,可使用if来判断临界值。并不须要while(xxx)作处理。 而对于多生产者或多消费则须要使用while处理,同时须要使用notifyAll去唤醒。不然可能出现假死的状况,即生产者和消费者都处于wait,所以notify不单单能够唤醒异类,也能够唤醒同类(即生产者也能够唤醒另外一个生产者)ide