两种写法
第一种 普通的 有个容器 有两条线程 去访问 大概就是这样的
#注意点 : 要去加个判断 然后等 还需要有人来唤醒 这就比较麻烦了
所以说 直接就来了第二种 阻塞队列 来解决这一些列的问题 了 首先就是阻塞队列的特点
Void put(E e) 将指定元素插入到次队列中,如果没有可用空间则等待;(一直等下去不吧QAQ )
E tke() 获取并移除此队列头部 如果没有可用元素 则等待 。(根它一样 哈哈哈 )
所以有了这两点之后 就根本不用我们再去做判断了 去解决生产者与消费者问题 就很安全 了
如图所示 ;

详细代码 如下 :
package qf.zz.wjpdemo01;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestBlockingQueue {
public static void main(String[] args) {
Storge s= new Storge() ;
ExecutorService es = Executors.newFixedThreadPool(2);
Long sttic =System.currentTimeMillis();
es.submit(new shengchan(s));
es.submit(new xiaofei(s));
es.shutdown();
System.out.println(System.currentTimeMillis()-sttic);
}
}
// 容器
class Storge{
// 创建了一个 阻塞队列
private BlockingQueue bq = new ArrayBlockingQueue<>(20);
// 生产者
public void shenchan(){
// 使用put方法 无期限等待
try {
bq.put(new Object());
System.out.println(Thread.currentThread().getName()+" 冲鸭 生产者 …");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 消费者
public void xiaofei(){
try {
// 使用take方法 不用做判断 直接死等就完事了
bq.take();
System.out.println(Thread.currentThread().getName()+" 冲鸭 消费者 。。。。");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 消费者
class xiaofei implements Runnable{
Storge s ;
public xiaofei() {}
public xiaofei(Storge s) {
this.s= s ;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 1; i <=10000; i++) {
s.xiaofei();
}
}}
// 生产者
class shengchan implements Runnable{
Storge s ;
public shengchan() {}
public shengchan(Storge s) {
this.s= s ;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i <=10000; i++) {
s.shenchan();
}
}}