定义好生产者和消费者之后,交给阻塞队列,阻塞队列自己控制生产和消费
代码语言:javascript复制package jucTest;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class MyResource{
public volatile boolean flag=true;//定义一个开关,开启生产和消费
private AtomicInteger atomicInteger=new AtomicInteger();
BlockingQueue<String> blockingQueue=null;
public MyResource(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
System.out.println(blockingQueue.getClass().getName());
}
//定义生产者
public void MyProduct() throws InterruptedException {
String date=null;
boolean result;
while (flag)
{
date = atomicInteger.incrementAndGet() "";
result = blockingQueue.offer(date, 2L, TimeUnit.SECONDS);
if (result==true){
System.out.println(Thread.currentThread().getName() " 生产" String.valueOf(date) " 成功");
}else{
System.out.println(Thread.currentThread().getName() " 生产" String.valueOf(date) " 失败");
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println("老板不让干了,生产结束");
}
//定义消费者
public void MyCustomer() throws Exception{
String poll=null;
while (flag){
poll= blockingQueue.poll(2L, TimeUnit.SECONDS);
if (poll==null||poll.equalsIgnoreCase("")){
System.out.println(" 消费时间超过2S,退出");
System.out.println();
System.out.println();
return;
}else {
System.out.println("消费" String.valueOf(poll) "成功");
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println("消费结束");
}
}
public class test2 {
public static void main(String[] args){
MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));
new Thread(()->{
System.out.println("生产线程启动");
try {
myResource.MyProduct();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"producer").start();
new Thread(()->{
System.out.println("消费者线程启动");
try {
myResource.MyCustomer();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
},"customer").start();
//暂停线程
try{ TimeUnit.SECONDS.sleep(10);} catch(InterruptedException e){ e.printStackTrace();}
System.out.println("10秒时间到,老板不让干了,下班了");
myResource.flag=false;
}
}
控制台打印