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());
}
}
===================测试结果如下:
分享到:
相关推荐
迷宫问题用队列解决,并求得最短路径,绝对源码
配套代码讲解:https://blog.csdn.net/songchuwang1868/article/details/90200251 ...同步队列-无锁队列-循环数组无锁队列 同步队列-无锁队列-循环数组无锁队列 同步队列-无锁队列-循环数组无锁队列
这个文档详细的介绍了利用栈和队列解决迷宫问题的步骤,对与初学者学习数据结构能很好的进行辅导
用循环队列解决约瑟夫环问题减少用顺序表在出对是循环移动带来的空间复杂度
用C#实现任务队列,一个队列存放任务,线程互斥的从任务队列中取,放任务,任务队列为空,线程等待,直到有任务加入队列为止。
利用栈和队列解决八皇后问题、N皇后问题-数据结构课程设计报告
Android中的线程池与任务队列
PI解决队列堵塞问题
C++数据结构练习题,利用队列解决迷宫问题,完成出路的寻找
男女排两列,依次入队进行搭配跳舞,多余人数留在下一次进行跳舞
使用redis做任务队列分发子任务,用于分布式拆分子任务提高系统运行效率
Java并发大神Doug Lee同步队列论文
互联网延迟队列解决方案设计.pdf
管理实时任务和延时任务,并提供任务状态管理。 实时任务:将任务存入DB,并放入消息队列。业务订阅队列消息,处理业务逻辑,根据需要结束任务。未结束的任务超时后自动重新放入消息队列,继续处理。
摸索出来这个的原因 是由于需要有序的播放多个声音的原因 需要以任务队列的形式 完成一个任务继续下一个 后面发现任务队列本身因为是后台的 发现跑同一个接口但次数很多的时候很好用
使用QQueue, QThread,QMutex,QWaitCondition模拟消息队列的任务处理,实现任务的同步处理
GCD 是苹果开发的应对多核编程,本实例总结了 GCD 三种队列的获取和创建,以及两种执行任务的方法。
主要介绍了使用队列(Queue)解决简单的并发问题,讲解的很细致,喜欢的朋友们可以了解一下
redis、delayqueue相关代码https://blog.csdn.net/sinat_38273626/article/details/80483014
huey:小型多线程任务队列