生产者与消费者,三个主要关键字:synchronized_wait_notifyAll
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
public class ProCustom_value<T> {
private LinkedList<T> lists=new LinkedList<>();
private int MAX=10; //最多装10
private int count=0; //当前0个
/*
* 生产者
*/
public synchronized void put(T t){
while(lists.size() == MAX){ //装满了//循环检查
try{
this.wait(); //阻塞,释放锁,wait和while绝配
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"生产-->"+t);
lists.add(t);
++count;
this.notifyAll(); //通知消费者线程进行消费
}
/*
* 消费者
*/
public synchronized T get(){
T t=null;
while(lists.size()==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t=lists.removeFirst();
count--;
this.notifyAll(); //通知生产者生产
return t;
}
public static void main(String[] args) {
final ProCustom_value<String> c=new ProCustom_value<>();
//启动消费者线程
for(int i=0;i<10;i++){
new Thread(new Runnable() { //创建10个线程消费
public void run() {
while(true){
System.out.println("消费-->"+c.get());
}
}
},"c"+i).start();
}
try {
TimeUnit.SECONDS.sleep(2); //睡2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
//启动生产者线程
for(int i=0;i<2;i++){
new Thread(new Runnable() {
public void run() {
while(true){
c.put(Thread.currentThread().getName()+"食品");
}
}
},"p"+i).start();
}
}
}
mark:学习笔记