以下是我的想法:
ServerThread implements Runnable{
run(){
BlockingQueue q = new ArrayBlockingQueue(1024);
ListenerThread lt = new ListenerThread8(q);
lt.start();
....
q.put(message);
}
}-T2将等待队列中的元素并处理它们。
ListenerThread implements Runnable{
...
run(){
while(run){
if(!q.isEmpty){
sendMessage(q.getfirst());
}else{
sleep(1000);
}
}
}
}这只是一个伪实现,我想如何实现我的部分程序。
-Could这个作品?
-And可以使用队列中的静态修饰符吗?
发布于 2015-03-12 09:03:21
这是生产者-消费者的自然模式,所以是的,这将是可行的。
顺便说一句,您不需要检查队列是否为空,只需调用take,它就会等到有什么东西出现。
class Thing {
}
class ServerThread implements Runnable {
@Override
public void run() {
BlockingQueue<Thing> q = new ArrayBlockingQueue<>(1024);
ListenerThread lt = new ListenerThread(q);
new Thread(lt).start();
q.put(message);
}
}
class ListenerThread implements Runnable {
volatile boolean run;
private final BlockingQueue<Thing> q;
public ListenerThread (BlockingQueue<Thing> q) {
this.q = q;
}
@Override
public void run() {
while (run) {
try {
sendMessage(q.take());
} catch (InterruptedException ex) {
run = false;
}
}
}
}您不应该需要使队列static。
我建议的唯一调整是不要在服务器run方法中创建侦听器。服务器应该尽可能少地了解消费者。队列、服务器和使用者都应该创建并连接到其他地方。
https://stackoverflow.com/questions/29005278
复制相似问题