Queue actually works now, as well as Thread.

This commit is contained in:
Julien Lengrand-Lambert
2020-04-10 15:54:29 +02:00
parent 6a546df7b8
commit 3043ed94a2
3 changed files with 22 additions and 18 deletions

View File

@@ -36,7 +36,7 @@ public class CommandGenerator {
private class CommandTimerTask extends TimerTask{
private int generatorId;
private Queue queue;
private volatile Queue queue;
public CommandTimerTask(int id, Queue queue){
this.queue = queue;

View File

@@ -3,34 +3,35 @@ package nl.lengrand.patterns.command;
import nl.lengrand.patterns.command.commands.Command;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
public class CommandProcessor implements Runnable {
private Queue<Command> queue;
private boolean running = false;
private volatile Queue<Command> queue;
private final AtomicBoolean running = new AtomicBoolean(true);
public CommandProcessor(Queue queue){
this.queue = queue;
}
public void start(){
System.out.println("Starting processor");
this.running = true;
this.run();
}
public void stop(){
this.running = false;
System.out.println("Stopping CommandProcessor");
this.running.set(false);
}
@Override
public void run() {
while(!queue.isEmpty()){
while(this.running.get()){
// Command Processors process items in the queue as fast as possible
var item = queue.poll();
if(item != null) item.execute();
System.out.println(queue.size() + " items left in queue");
if(item != null) {
item.execute();
}
else{
System.out.println("Empty queue. Stopping Processor");
this.stop();
}
}
return;
}
}

View File

@@ -5,6 +5,7 @@ import nl.lengrand.patterns.command.commands.Command;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@@ -20,22 +21,24 @@ public class ProcessingQueueExample {
public static void main(String[] args) throws InterruptedException {
Queue<Command> queue = new LinkedList<>();
int numberGenerators = 5;
List<CommandGenerator> generators = IntStream.range(0, 5)
.mapToObj(i -> new CommandGenerator(i + 1, queue, getRandomInterval()))
.collect(Collectors.toList());
generators.forEach(g -> g.generate());
Thread.sleep(2000);
Thread.sleep(1000);
CommandProcessor processor = new CommandProcessor(queue);
processor.start();
Thread processorThread = new Thread(processor);
System.out.println("Starting");
processorThread.start();
Thread.sleep(200);
generators.forEach(g -> g.stop());
}
/*
Returns a random integer between 1 and 1000 (representing between 1 and 1000 ms interval)
*/