线程通信: wait():令当前线程挂起并放弃CPU,需要被唤醒(notify()--唤醒优先级最高的线程或者notifyAll())才能继续被允许继续使用。
生产--消费者问题: 这个是多线成中重要的问题,下面是一个小案例,生产者生产商品,当仓库满了以后,停止生产,消费者消费商品,当仓库的商品被消耗完毕之后,停止消耗
案例:
仓库类:
import java.util.ArrayList;
public class Store {
//可以通过ArrayList的构造方法更改其初始容量为100
public static ArrayList<Object> list=new ArrayList<>(100);
public static Integer MAX_NUM=100;
}
生产者类:
生产者:
public class Producer extends Thread{
@Override
public void run(){
while (true) {
synchronized (Store.list){
if (Store.list.size() < Store.MAX_NUM) {
//这个生产者马上要开始生产了,可以唤醒消费者进行消费商品(用唯一对象实现)
Store.list.notify();
//生产
Object obj = new Object();
Store.list.add(obj);
System.out.println(Thread.currentThread().getName() +
"-生产商品,仓库目前的数量:" + Store.list.size());
} else {
//停止生产
System.out.println(Thread.currentThread().getName()+"-仓库已满停止生产");
//停止生产以后要进入等待
try {
Store.list.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
消费者类:
public class Consumer extends Thread{
@Override
public void run(){
while (true){
synchronized (Store.list){
//消费
if (Store.list.size()>0){
Store.list.notify();
Store.list.remove(0);
System.out.println(Thread.currentThread().getName()+"-消费商品,仓库目前数量:"+Store.list.size());
}else {
//停止消费
System.out.println(Thread.currentThread().getName()+"-仓库已满,停止生产");
try {
Store.list.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
测试类: 启动主进程,既可以观察生产-消费者关系
//测试者类
public class StoreTest {
public static void main(String[] args) {
Producer p = new Producer();
Consumer c = new Consumer();
p.start();
c.start();
}
}