Queuing processes - java
I need to do it in java, so that I can put processes in a queue and they are executed in turn.
Tipo: One process monitors the queue, if the queue is not equal to 0, it starts processes from this queue
How to implement this correctly, I just tried and then nothing works for me
Queue:
Queue<Thread> queue = new LinkedList<>();
The process monitoring the queue:
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (queue.size() != 0) {
Thread th = queue.peek();
queue.remove();
th.start();
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
Function for adding processes to the queue:
private void sendToDevice(final String string) {
queue.add(new Thread(new Runnable() {
@Override
public void run() {
try {
outStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}));
}
2
1 answers
Try this way:
ExecutorService service1 = Executors.newSingleThreadExecutor();
service1.execute(new Runnable() {
//и здесь твой код
});
1
Author: KvaksMan play, 2020-04-26 14:32:19