使用同步队列解决任务协作问题

本文介绍了Java API中提供的同步队列,通过一个基本线程类LiftOff实例,展示了如何使用同步队列解决任务协作问题。包括了ArrayBlockingQueue和SynchronousQueue的具体应用。

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

Java API里面提供了许多同步队列,你可以使用它来解决任务协作问题。同步队列在任何时刻都只允许一个任务插入或移除元素。例子如下:


===============基本线程类

public class LiftOff implements Runnable {   
protected int countDown = 10;
private static int taskCount = 0;
private final int id = taskCount++;

public LiftOff() {
}

public LiftOff(int countDown) {
this.countDown = countDown;
}

public String status() {
return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "),";
}

@Override
public void run() {
while (countDown-- > 0) {
System.out.println(status());
Thread.yield();
}
}

}


==============================

public class LiftOffRunner implements Runnable{

private BlockingQueue rockets;

public LiftOffRunner(BlockingQueue queue) {
// TODO Auto-generated constructor stub
rockets=queue;
}

public void add(LiftOff lo){
try {
rockets.put(lo);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//BloIllegalStateException
}


@Override
public void run() {
// TODO Auto-generated method stub
try {
while(!Thread.interrupted()){
LiftOff rocket=rockets.take();
rocket.run();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Weaking From take()");
}
System.out.println(" Exiting LiftOffRunner()");
}
}

=========================测试类TestBlockingQueues

public class TestBlockingQueues {

static void getKey(){
try {
new BufferedReader(new InputStreamReader(System.in)).readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}

}


static void getKey(String message){
System.out.println(""+message);
getKey();
}


static void test(String msg,BlockingQueue queue)
{
System.out.println(msg);
LiftOffRunner runner=new LiftOffRunner(queue);
Thread t=new Thread(runner);
t.start();
for(int i=0;i());
test("ArrayBlockingQueue",new ArrayBlockingQueue(3));
test("SynchronousQueue",new SynchronousQueue());


}
}
===================测试结果如下:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值