I have the following code.
I am trying to:
Assign a bukkit runnable task to a given ID
Assign a player a given ID
Place these two IDs into a hashmap, where each participant is matched to their respective bukkit runnable task
The repeating task should assign a maximum of 4 objects to a given player's inventory, assigning one object every minute.
This means that for each player, the repeating task should last a maximum of 4 minutes and should be cancelled when the counter exceeds the length of the hashmap.
However, I get the issue 'the local variable task may not have been initialised'.
I know that this means that I should initialise the variable 'task', but I am not sure how to do so, given that the variable task corresponds to the bukkit runnable task?
I would be so grateful for a helping hand!
Map<UUID, Integer> map = new HashMap<UUID, Integer>();
List<ItemStack> items = java.util.Arrays.asList(
new ItemStack(Material.WATER),
new ItemStack(Material.COBWEB),
new ItemStack(Material.CAKE),
new ItemStack(Material.RED_WOOL)
);
#EventHandler
public void on(PlayerQuitEvent event) {
map.remove(event.getPlayer());
}
#EventHandler
public void on(PlayerInteractEvent event) {
final ItemStack item = event.getItem();
if (item.getType() == Material.WHITE_WOOL) {
BukkitTask task = getServer().getScheduler().runTaskTimer(this, () -> {
if(this.stopRepeater) {
int counter = 0;
while (counter <= 4){
Material[] listofitems = {Material.WATER, Material.COBWEB, Material.CAKE, Material.SNOW};
int idx = counter;
Material randomItem = listofitems[idx];
ItemStack items = new ItemStack(randomItem);
Player thePlayer = event.getPlayer();
thePlayer.getInventory().addItem(items);
map.put(event.getPlayer().getUniqueId(),task.getTaskId());
counter ++;
if (counter >= map.size()) {
Bukkit.getServer().getScheduler().cancelTask(task.getTaskId());
}
}
}
}, 20 * 60, 20 * 60);
}
}
You might be able to get around this by splitting the BukkitTask task = ... line into BukkitTask task; and task = ..., though I've not tested it.
Thank you for your help!
I have come up with the following solution:
#EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
new BukkitRunnable() {
int count = 0;
Material[] listofitems = {Material.WATER_BUCKET, Material.CACTUS, Material.CAKE, Material.SNOW};
public void run() {
if (count == listofitems.length-1) cancel();
Material nextItem = listofitems[count];
ItemStack item = new ItemStack(nextItem);
event.getPlayer().getInventory().addItem(item);
count++;
}
}.runTaskTimer(this, 1200L, 1200L);
}
}
v
The lib I'm using is processing library. I'm currently making a game and I need to remove items from list every 2 seconds after adding it (item will be add by Keypressed SPACE). I've tried this:
List<String> items = new ArrayList<>();
boolean timeStarted;
int timeDuration = 2000;
int startTime = 0;
if (timeStarted) {
int currentDuration = millis() - startTime;
if (currentDuration >= timeDuration) {
items.remove(0);
startTime = millis();
timeStarted = false;
}
}
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
if (keycode == 32) { // SPACE
startTime = millis();
timeStarted = true;
items.add("new item");
}
But this only remove the first item in the list, and it will stuck if I press the SPACE too fast (add too many items at the same time).
Could anyone help me or give me some idea how to deal with this? Thanks in advance!
I personally wouldn't mix and match threading and Processing together.
If you're using Processing, and are doing this for a game (thus probably dont require milisecond precision), why not just use the framerate as a time measurement? Your Processing programs are always supposed to run at a set frameRate (unless you have some performance issues). You also won't see anything happen untill the frame where the action happens has been drawn anyway, so it doesn't really matter if your action completed halfway between a frame, your end user won't see the difference.
The default frameRate in Processing is 30fps. You can set a custom rate using the frameRate() function (docs). frameCount returns the number of frames drawn (0 on the first frame).
Thus, you can do something like the following pseudocode
int removeItemCheckpoint;
int removeItemDuration;
void setup()
{
// 30 frames per second
frameRate(30);
// window is two seconds, so this duration will last two times the frameRate
removeItemDuration = frameRate * 2;
}
void draw()
{
if (some input)
{
// set checkpoint to current frame count + the duration
removeItemCheckpoint = frameCount + removeItemDuration;
}
// if current frame count is larger than the checkpoint, perform action
if (frameCount > removeItemCheckpoint)
{
// set checkpoint to pseudo infinity
removeItemCheckpoint = Integer.MAX_VALUE;
// remove item here
}
}
If you want to handle this for multiple objects at a time, you could create something like a list of created list index/checkpoint pairs and loop over those instead.
List<Pair<int, int>> toBeRemoved = new List<Pair<int, int>>();
// add a new pair
toBeRemoved.add(new Pair(itemIndex, frameCount + removeItemDuration));
// loop over the list
foreach (Pair<int, int> item in toBeRemoved)
{
if (frameCount > item.getKey())
{
itemList.remove(item.getValue());
}
}
Use while for checking element from list 2 seconds after adding.
// remove element from list 2 seconds after adding it
while (startedTime+timeDuration >= System.currentTimeMillis()) {
// If delete exit while
items.remove(0);
break;
}
and Use thread for removing your item when you can keypress space.
if (keycode == 32) { // SPACE
long startTime = System.currentTimeMillis();
items.add("new item");
// Thread execute
Thread thread = new Thread(new Remover(startTime, items));
thread.start();
}
#Override
public void run() {
// remove element from list 2 seconds after adding it
while (startedTime+timeDuration >= System.currentTimeMillis()) {
// If delete exit while
items.remove(0);
break;
}
// whether item is deleted
System.out.println(items);
}
Full code
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.keyPressed(32);
}
// Integer instead of Keycode
public void keyPressed(Integer keycode) {
List<String> items = new ArrayList<String>();
if (keycode == 32) { // SPACE
long startTime = System.currentTimeMillis();
items.add("new item");
// Check items
System.out.println(items);
// Thread execute
Thread thread = new Thread(new Remover(startTime, items));
thread.start();
}
}
}
class Remover implements Runnable{
List<String> items;
int timeDuration = 2000;
long startedTime;
public Remover(long startedTime,List<String> items) {
this.startedTime = startedTime;
this.items = items;
}
#Override
public void run() {
// remove element from list 2 seconds after adding it
while (startedTime+timeDuration >= System.currentTimeMillis()) {
// If delete items,Exit while
items.remove(0);
break;
}
// whether item is deleted
System.out.println(items);
}
}
I'm making a snake game and I've encountered an error.
I have tried two different loops: thread.sleep and Timer.schedule.
I have gotten the same problem.
It will be working fine, but at random intervals, it will start to skip every other frame for 6-10 frames.
In case I wasn't clear, 1 frame is
#Override public void paintComponent(Graphics G){...}
being called. (I have also tried paint)
This has occurred in some other games I've created, but not all. What can I do to fix it?
Here's a full copy of the code:
https://github.com/jnmcd/Snake/blob/master/Code.java
EDIT: I've done some debugging. It appears that the it's not a problem with the paint. The JPanel doesn't always update. What can I do to fix it?
I found what I needed to do. I had to add a revaidate() after the repaint().
Also In the checkKillCollisions you have to break the loop right after you found the losing condition.
Also if the game ends it keeps on showing the error message[Dialog] for which there i no end.So I have created a flag gameOver to check is game is over or not in Snake Class
static Boolean gameOver = false;//Defined in Snake Class
public void checkKillCollisions() {
boolean lose = false;
for (int i = 1; i < Snake.segments.size(); i++) {
if (Snake.segments.get(i).x == x && Snake.segments.get(i).y == y) {
lose = true;
break;//Have to do this
}
}
if (x >= 60 || x < 0 || y >= 60 || y < 0) {
lose = true;
}
if (lose) {
Snake.window.popUp("You Lose");
}
Snake.gameOver = lose;//Will set the gameOVer flag in Snake class
}
And I've modified the Loop class to stop running right after the gameOver flag is set to true
class Loop extends TimerTask {
#Override
public void run() {
if (!Snake.gameOver) {
Snake.updates();
Snake.window.render();
} else {
System.out.println("Game Over");
cancel();
Snake.window.dispose();
}
}
}
in my app I have a timer and stop/start buttons. Timer works with thread
when I click the button my timer starts working. when I click stop and start it seems like my thread works as 2 parallel threads.
How to stop the first thread and create the second ?
Here is the code
timer = new Thread(new Runnable() {
#Override
public void run() {
final boolean cont = mSharedPreferences.getBoolean("continuesMode", false);
final boolean statemant = !stopedAlgo && !mUserStop;
if(!statemant){
timerMinutes = 0;
timerHours = 0;
}
while(statemant){
time="";
if(timerMinutes>=60){
timerMinutes = 0;
timerHours++;
}
if(timerHours<10)
time = "0" + String.valueOf(timerHours)+":";
else
time = String.valueOf(timerHours)+":";
if(timerMinutes<10)
time += "0" + String.valueOf(timerMinutes);
else
time += String.valueOf(timerMinutes);
HeadSense.this.runOnUiThread(new Runnable(){
public void run(){
boolean state = mContinuousMode && !stopedAlgo && !mUserStop ;
if(!stopedAlgo && cont){
mTfsValue.setText(time);
timerMinutes++;
}
else{
timerMinutes = 0;
timerHours = 0;
}
}
});
try {
Thread.sleep(1*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
timer.start();
Of my understanding your first Thread (or second) will never stop because of the following line:
final boolean statemant = !stopedAlgo && !mUserStop;
This is final, and will only be evaluated once and never change. If it evalutes to true when you create the Thread it will stay true and keep running.
You need to declare your boolean statemant as volatile here. What this does is give a hint to the compiler that certain optimizations cannot be taken because this variable is modified by external threads.
Also, you would be interested in this - How to stop a java thread gracefully?
I have created three threads in a java program. One is the main program, the others are two classes that extend Thread. The main thread represent a controller for a machine. Another thread is the actuators and the third is the sensors. The controller sets variables in its own class which is read by the actuator thread. The actuator performs certain actions according to the instructions and update its own internal variables. These are in turn read by the sensor thread which reads the actuator variables (representing real world actions) and sets its own internal variables which in turn is read by the controller and we have come full circle. The controller then sets variables according to the new sensed world etc.
The actuators are in a eternal loop sleeping 100 ms in each loop.
The sensors are also in an eternal loop sleeping 20ms per loop.
The system almost works. The main loop will miss the updates from the sensor unless I add a sleep to it as well. My question is now why that is? Even sleep(0) makes the system work. I've placed the statement inside the performJob(Job input) while loop. How does the java main thread without a sleep call act differently than the same thread with?
Concurrency is a fairly new subject to me.
This is the code I am using:
Main:
public class Main {
public static void main(String[] args) {
Controller Press = new Controller();
Press.processUnits(1); // no reset code at the moment, only use 1 at a time
Press.shutdownThreads();
}
}
Controller:
import java.util.LinkedList;
public class Controller extends Thread {
// Constants
static final int STATE_WAITING = 0;
static final int STATE_MOVE_ARMS = 1;
static final int STATE_MOVE_PRESS = 2;
static final int LOADINGARM = 2;
static final int UNLOADINGARM = 1;
static final int NOARM = 0;
static final boolean EXTEND = true;
static final boolean RETRACT = false;
private enum Jobs {
EXTENDRETRACT, ROTATE, MAGNETONOFF, PRESSLOWERRAISE
}
// Class variables
private int currentState;
// Component instructions
private int armChoice = 0;
private boolean bool = false; // on, up, extend / off, down, retract
private boolean[] rotInstr = {false, false}; // {rotate?, left true/right false}
private boolean errorHasOccurred = false;
private boolean pressDir = false;
private Sensors sense = null;
private Actuators act = null;
private LinkedList<Job> queue = null;
// Constructor
public Controller() {
act = new Actuators(0.0f, this);
sense = new Sensors();
act.start();
sense.start();
currentState = STATE_WAITING;
queue = new LinkedList<Job>();
}
// Methods
int[] getArmInstructions() {
int extret = (bool) ? 1 : 0;
int[] ret = {armChoice, extret};
return ret;
}
boolean[] getRotation() {
return rotInstr;
}
int getControllerState() {
return currentState;
}
boolean getPressDirection() {
return pressDir;
}
public boolean processUnits(int nAmount) {
if (run(nAmount)) {
System.out.println("Controller: All units have been processed successfully.");
return true;
} else { // procUnits returning false means something went wrong
System.out.println("Controller: An error has occured. The process cannot complete.");
return false;
}
}
/*
* This is the main run routine. Here the controller analyses its internal state and its sensors
* to determine what is happening. To control the arms and press, it sets variables, these symbolize
* the instructions that are sent to the actuators. The actuators run in a separate thread which constantly
* reads instructions from the controller and act accordingly. The sensors and actuators are dumb, they
* will only do what they are told, and if they malfunction it is up to the controller to detect dangers or
* malfunctions and either abort or correct.
*/
private boolean run(int nUnits) {
/*
Here depending on internal state, different actions will take place. The process uses a queue of jobs
to keep track of what to do, it reads a job, sets the variables and then waits until that job has finished
according to the sensors, it will listen to all the sensors to make sure the correct sequence of events is
taking place. The controller reads the sensor information from the sensor thread which runs on its own
similar to the controller.
In state waiting the controller is waiting for input, when given the thread cues up the appropriate sequence of jobs
and changes its internal state to state move arms
In Move arms, the controller is actively updating its variables as its jobs are performed,
In this state the jobs are, extend, retract and rotate, pickup and drop.
From this state it is possible to go to move press state once certain conditions apply
In Move Press state, the controller through its variables control the press, the arms must be out of the way!
In this state the jobs are press goes up or down. Pressing is taking place at the topmost position, middle position is for drop off
and lower is for pickup. When the press is considered done, the state reverts to move arms,
*/
//PSEUDO CODE:
//This routine being called means that there are units to be processed
//Make sure the controller is not in a blocking state, that is, it shut down previously due to errors
//dangers or malfunctions
//If all ok - ASSUMED SO AS COMPONENTS ARE FAULT FREE IN THIS VERSION
if (!errorHasOccurred) {
//retract arms
currentState = STATE_MOVE_ARMS;
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, RETRACT));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, RETRACT));
performWork();
//System.out.println("Jobs added");
//while there are still units to process
for (;nUnits != 0; nUnits--) {
//move the press to lower position, for unloading
currentState = STATE_MOVE_PRESS;
//rotate to pickup area and pickup the metal, also pickup processed
currentState = STATE_MOVE_ARMS;
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, EXTEND));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, EXTEND));
performWork();
//retract and rotate
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, RETRACT));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, RETRACT));
performWork();
//state change, press moves to middle position
currentState = STATE_MOVE_PRESS;
//state change back, put the metal on the press, drop processed and pull arms back
currentState = STATE_MOVE_ARMS;
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, EXTEND));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, EXTEND));
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, RETRACT));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, RETRACT));
performWork();
//state change, press the metal in upper position
currentState = STATE_MOVE_PRESS;
//repeat until done
}
//unload final piece
//move the press to lower position for unload
//rotate and pickup processed piece
//drop it off at unloading and wait for more orders
currentState = STATE_WAITING;
}
return true;
}
private boolean performWork() {
while (!queue.isEmpty()) {
performJob(queue.removeFirst());
}
return true;
}
private boolean performJob(Job input) {
//The purpose of this function is to update the variables and wait until they are completed
// read in the job and check appropriate sensors
boolean[] data = sense.getSensorData(); // LExt, LRet, UlExt, UlRet
printBools(data);
int Instruction = input.Instruction;
boolean skipVars = false;
if (input.Job == Jobs.EXTENDRETRACT) {
if (currentState != STATE_MOVE_ARMS){
System.out.println("Wrong state in performJob. State is "+currentState+" expected "+STATE_MOVE_ARMS);
return false;
}
if ((Instruction == LOADINGARM) && (input.Bool)) skipVars = data[0];
if ((Instruction == LOADINGARM) && (!input.Bool)) skipVars = data[1];
if ((Instruction == UNLOADINGARM) && (input.Bool)) skipVars = data[2];
if ((Instruction == UNLOADINGARM) && (!input.Bool)) skipVars = data[3];
}
if (!skipVars) {
// if sensors not at intended values, update correct variables
System.out.println("Controller: Did not skip vars");
switch (input.Job) {
case EXTENDRETRACT:
armChoice = (Instruction == LOADINGARM) ? LOADINGARM : UNLOADINGARM;
bool = input.Bool;
break;
case ROTATE:
break;
case MAGNETONOFF:
break;
case PRESSLOWERRAISE:
break;
default:
System.out.println("Default called in performJob()");
break;
}
}
// listen to sensors until completed
boolean done = false;
System.out.println("Waiting for sensor data.");
//System.out.print("Instruction is "+Instruction+" and bool is "); if (input.Bool) System.out.print("true\n"); else System.out.print("false\n");
while (!done) {
data = sense.getSensorData();
// REMOVING THIS TRY STATEMENT BREAKS THE PROGRAM
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
System.out.println("Main thread couldn't sleep.");
}
// Check appropriate sensors
if (input.Job == Jobs.EXTENDRETRACT) {
if ((Instruction == LOADINGARM) && (input.Bool)) done = data[0];
if ((Instruction == LOADINGARM) && (!input.Bool)) done = data[1];
if ((Instruction == UNLOADINGARM) && (input.Bool)) done = data[2];
if ((Instruction == UNLOADINGARM) && (!input.Bool)) done = data[3];
}
}
// reset all variables
armChoice = 0;
bool = false;
// when done return
System.out.println("Finished "+input.Job);
return true;
}
public void shutdownThreads() {
sense.shutDown();
act.shutDown();
}
private class Job {
// Class variables
Jobs Job;
int Instruction;
boolean Bool; // used for directions, up/down, left/right, extend/retract
// Constructor
Job(Jobs newJob, int newInstruction, boolean dir) {
Job = newJob;
Instruction = newInstruction;
Bool = dir;
}
}
private void printBools(boolean[] input) {
System.out.println();
for (int i = 0; i < input.length; i++) {
if (input[i]) System.out.print("true "); else System.out.print("false ");
}
System.out.println();
}
}
Actuators:
public class Actuators extends Thread {
// Constants
private final int ARM = 0, ROTATE = 0; // array indexes - which arm, rotate yes/no?
private final int DIR = 1, ROTDIR = 1; // array indexes - which direction ext/ret, rotate direction
private final int EXT = 1;//, RET = 0;
private final double ARM_SPEED = 5.0;
// Class variables
private Controller Owner = null;
private boolean run = true;
// Constructor
Actuators(float nPos, Controller Owner) {
Reality.changeAngle(nPos);
this.Owner = Owner;
}
// Methods
private void rotate(boolean dir) {
float nAngle = dir ? 0.1f : -0.1f;
Reality.changeAngle(nAngle);
}
public void run() {
while (run) {
try {
sleep(100);
} catch (InterruptedException e) {
System.out.println("Actuators couldn't sleep");
}
// read variables in controller
int nState = Owner.getControllerState();
if (nState == Controller.STATE_MOVE_ARMS) {
boolean[] rot = Owner.getRotation();
if (rot[ROTATE]) { // Rotation?
rotate(rot[ROTDIR]);
} else { // or arm extensions
int[] instr = Owner.getArmInstructions();
if (instr[ARM] != Controller.NOARM) { // 0 = no arm movement
//System.out.println("Actuator arm is "+instr[ARM]);
double dir = (instr[DIR] == EXT) ? ARM_SPEED : -ARM_SPEED; // 1 = extend, 0 = retract
Reality.changeArmLength(instr[ARM], dir);
}
}
}
}
}
void shutDown() {
run = false;
}
}
Reality is a class composed of static fields and methods, written to by the actuators and read by sensors.
public class Reality {
// Constants
static private final double EXTEND_LIMIT = 100.0;
static private final double RETRACT_LIMIT = 0.0;
// Variables
private static float ArmsAngle = 0.0f;
// Read by Sensor
static double LoadingArmPos = 0.0;
static double UnloadingArmPos = 0.0;
// Methods
static void changeAngle(float newAngle) {
ArmsAngle = ArmsAngle + newAngle;
if ((ArmsAngle < 0.0f) || (ArmsAngle > 90.0f))
System.out.println("Reality: Unallowed Angle");
}
static void changeArmLength(int nArm, double dPos) { // true = extend, false = retract
switch (nArm) {
case Controller.LOADINGARM:
LoadingArmPos += dPos;
checkArmPos(LoadingArmPos);
break;
case Controller.UNLOADINGARM:
UnloadingArmPos += dPos;
checkArmPos(UnloadingArmPos);
break;
default:
System.out.println("Arm other than 2 (load) or 1 (unload) in changeArmLength in Reality");
break;
}
}
static float senseAngle() {
return ArmsAngle;
}
static private boolean checkArmPos(double dPos) {
// Allowed positions are 100.0 to 0.0
if ((dPos > EXTEND_LIMIT) || (dPos < RETRACT_LIMIT)) {
System.out.println("Arm position impossible in reality. Is "+dPos);
return true;
} else {
return false;
}
}
}
Finally the sensors:
public class Sensors extends Thread {
// Constants
private final double EXTENDED = 100.0;
private final double RETRACTED = 0.0;
private final double MARGIN = 0.1;
// Class Variables
private boolean run = true;
// Read by Controller
private boolean LoadingExtended = true;
private boolean LoadingRetracted = true;
private boolean UnloadingExtended = true;
private boolean UnloadingRetracted = true;
// Constructor
Sensors() {
LoadingExtended = false;
LoadingRetracted = true;
UnloadingExtended = false;
UnloadingRetracted = true;
}
// Methods
boolean senseLoadingExtended() {
return (Math.abs(Reality.LoadingArmPos - EXTENDED) < MARGIN);
}
boolean senseLoadingRetracted() {
return (Math.abs(Reality.LoadingArmPos - RETRACTED) < MARGIN);
}
boolean senseUnloadingExtended() {
return (Math.abs(Reality.UnloadingArmPos - EXTENDED) < MARGIN);
}
boolean senseUnloadingRetracted() {
return (Math.abs(Reality.UnloadingArmPos - RETRACTED) < MARGIN);
}
// called by Controller
boolean[] getSensorData() {
boolean[] ret = {LoadingExtended, LoadingRetracted, UnloadingExtended, UnloadingRetracted};
return ret;
}
// Sensor primary loop
public void run() {
while (run) {
try {
sleep(20);
}
catch (InterruptedException e) {
System.out.println("Sensors couldn't sleep");
}
LoadingExtended = senseLoadingExtended();
LoadingRetracted = senseLoadingRetracted();
UnloadingExtended = senseUnloadingExtended();
UnloadingRetracted = senseUnloadingRetracted();
}
}
void shutDown() {
run = false;
}
}
Not all fields and functions are read in this version. The program is a reworking of a previous single thread application mostly using function calls. I've cleaned up the code a bit for readability. Constructive design remarks are welcome even though it was not the original question. There is something really fishy going on. I am usually not a superstitious coder but I can for example replace the sleep call with a System.out.println() call and the program will work.
Google for 'Producer consumer queue'.
Don't use sleep() for inter-thread comms unless you want latency, inefficiency and lost data. There are much better mechanisms available that avoid sleep() and trying to read valid data directly from some shared/locked object.
If you load up 'comms' objects with commands/requests/data, queue them off to other threads and immediately create another comms object for subsequent communication, your inter-thread comms will be fast and safe, no sleep() latency and no chance of any thread reading data that is stale or being changed by another thread.
What occurred here was most probably a Memory Consistency Error. When the controller class set the internal control variables and then entered the loop waiting for sensors it most likely prevented the Actuators and Sensors classes from properly updating the readings seen to the controller and as such prevented the controller from seeing the correct values. By adding the synchronize statement to all functions which read from another class the problem was solved. I can only speculate that the sleep call had the controller thread enter a synchronized block of some kind which let the other threads' changes to the variables become visible.
Which JVM are you using?
As fast workaround you can set volatile for fields that shared between threads.
Also please look to actors' approach for messaging: http://doc.akka.io/docs/akka/snapshot/java/untyped-actors.html