public class Main {
public static boolean isToggled = false;
public static boolean isClicking = false;
public static void main(String[] args){
while(true){
if(Main.isToggled && Main.isClicking){
System.out.println("Running");
}
}
}
I have two public static booleans with the value of false in my Main class.
A while(true) loop will constantly check, if both booleans are set to true, by another class.
However, if both conditions are being set to true, nothing happens.
The while loop only works, if an else statement is added to it like this:
public class Main {
public static boolean isToggled = false;
public static boolean isClicking = false;
public static void main(String[] args){
while(true){
if(Main.isToggled && Main.isClicking){
System.out.println("Running");
}
else{
System.out.println("Idle");
}
}
}
So it is definitely the while loop that is the problem.
The class which sets the conditions to true works perfectly fine. I've tested that by removing the while loop, and just printing the value of the booleans after their value has changed.
I don't understand, why the first code isn't doing what its supposed to, when the other one with the else statement added to it does.
Copy code to test:
public class Main {
public static boolean isToggled = false;
public static boolean isClicking = false;
public static void main(String[] args) {
Thread changeBoolsT = new Thread(new Runnable() {
@Override
public void run() {
changeBools();
}
});
changeBoolsT.start();
while(true){
if(isToggled && isClicking){
System.out.println("OK");
break;
}
else{ // Remove this else statement
System.out.println("Waiting");
}
}
}
public static void changeBools(){
try{
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isToggled = true;
isClicking = true;
}
}