The following scneario is what i was thinking of:
- 2 Threads, 1 Producer, 1 Consumer
- T1 creates the Queue and starts the next thread, and is repsonsible for puting elements into the queue
ServerThread implements Runnable{
run(){
BlockingQueue q = new ArrayBlockingQueue(1024);
ListenerThread lt = new ListenerThread8(q);
lt.start();
....
q.put(message);
}
}
-T2 will wait for elements in the queue and handles them
ListenerThread implements Runnable{
...
run(){
while(run){
if(!q.isEmpty){
sendMessage(q.getfirst());
}else{
sleep(1000);
}
}
}
}
This is just a pseudo implementation of how i want to implement my part of the program.
-Could this work?
-And could this work with the static modifier on the queue?
This is the natural pattern for producer-consumer so yes this will work.
By the way - you don't need to check the queue to see if it is empty - you just need to call take
which will wait until something is there.
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;
}
}
}
}
You should not need to make the queue static
.
The only adjustment I would recommend would be to not create the listener inside the server run
method. The server should know as little as possible about the consumer. The queue, the server and the consumer should all be created and linked up someplace else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.