一 可阻塞队列介绍
可阻塞队列,用三个空间的队列来演示阻塞队列的功能和效果
public class BlockingQueueTest {/*
* 可阻塞队列,用三个空间的队列来演示阻塞队列的功能和效果
*/
public static void main(String[] args) {
final BlockingQueue queue = new ArrayBlockingQueue(3);
for(int i = 0;i<2;i++) {
new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep((long)Math.random()*1000);
System.out.println(Thread.currentThread().getName()+" 准备放数据了");
queue.put(1);
System.out.println(Thread.currentThread().getName()+" 已经放了数据,"+" 目前队列里面有"+queue.size()+"个数据");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" 准备取数据");
queue.take();
System.out.println(Thread.currentThread().getName()+" 已经取走数据,"+"目前队列里面有"+queue.size()+"个数据");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
执行结果:
示例代码2:子线程循环10次,主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次
采用阻塞队列的形式实现
public class BlockingQueueCommunication {
//子线程循环10次,主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次
public static void main(String[] args) {
final Business business =new Business();
new Thread(new Runnable() {
@Override
public void run() {
for(int j = 1; j <=50 ;j++) {
business.sub(j);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int j = 1; j <=50 ;j++) {
business.main(j);
}
}
}).start();
}
static class Business{
//采用阻塞队列的形式实现
BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);
//匿名构造方法
{
try {
queue2.put(1);
}catch (Exception e) {
}
}
public void sub(int j) {
try {
queue1.put(1);
} catch (Exception e) {
e.printStackTrace();
}
for(int i=1;i<=10;i++) {
System.out.println("sub thread sequnce of "+i+","+"loop of "+j);
}
try {
queue2.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void main(int j) {
try {
queue2.put(1);
} catch (Exception e) {
e.printStackTrace();
}
for(int i=1;i<=100;i++) {
System.out.println("main thread sequnce of "+i+","+"loop of "+j);
}
try {
queue1.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
执行结果: