线程基础(七)可阻塞队列ArrayBlockingQueue

本文通过两个示例展示了阻塞队列在多线程环境中的应用:一是使用固定大小的队列进行数据的生产和消费;二是利用阻塞队列协调主线程与子线程的任务执行顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 可阻塞队列介绍

 

 可阻塞队列,用三个空间的队列来演示阻塞队列的功能和效果

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();
}

 
}



}

执行结果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值