检测blockingqueue的功能
package com.concurrent;
import java.util.concurrent.BlockingQueue;
/**
* ClassName: consumer
* Description:
* date: 2021/12/12 22:11
*
* @author: 邱攀攀
* @version:
* @since JDK 1.8
*/
public class consumer extends Thread{
BlockingQueue<Integer> ssqueue;
consumer(BlockingQueue bq){
this.ssqueue = bq;
}
@Override
public void run(){
try {
while(!Thread.currentThread().isInterrupted()) {
Integer take = ssqueue.take();
System.out.println("我成功消费了一个");
sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.concurrent;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
/**
* ClassName: producer
* Description:
* date: 2021/12/12 22:03
*
* @author: 邱攀攀
* @version:
* @since JDK 1.8
*/
public class producer extends Thread {
BlockingQueue<Integer> ssqueue ;
private int i = 0;
producer(BlockingQueue bq){
this.ssqueue = bq;
}
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()) {
try {
ssqueue.add(i++);
System.out.println("我成功生产了一个");
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.concurrent;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* ClassName: test
* Description:
* date: 2021/12/12 22:16
*
* @author: 邱攀攀
* @version:
* @since JDK 1.8
*/
public class test {
public static void main(String[] args) {
BlockingQueue bq = new ArrayBlockingQueue(5);
consumer con = new consumer(bq);
producer p = new producer(bq);
con.start();
p.start();
}
}
将在blockingqueue为满时抛出异常,但不会终止程序,只会终止producer线程,之后consumer线程继续消费,直到为0,然后阻塞队列进入阻塞状态
但是当我们使用线程池时将不会抛出异常:
package com.concurrent;
import java.util.concurrent.*;
/**
* ClassName: test
* Description:
* date: 2021/12/12 22:16
*
* @author: 邱攀攀
* @version:
* @since JDK 1.8
*/
public class test {
public static void main(String[] args) {
BlockingQueue bq = new ArrayBlockingQueue(5);
consumer con = new consumer(bq);
producer p = new producer(bq);
ExecutorService executorService = Executors.newFixedThreadPool(20);
executorService.submit(con);
executorService.submit(p);
}
}
|