Can (a = = 1 \ u0026 \ u0026 a = = 2 \ u0026 \ u0026 a = = 3) be evaluated as true in Java?
We know it can in JavaScript.
But is it possible to print a "success" message under the conditions given below in Java?
if (a==1 && a==2 && a==3) { System.out.println("Success"); }
It was suggested that:
int _a = 1; int a = 2; int a_ = 3; if (_a == 1 && a == 2 && a_ == 3) { System.out.println("Success"); }
But by doing so, we are changing the actual variables Is there any other way?
Solution
Yes, if you declare variable a volatile, it's easy to use multiple threads
One thread keeps changing variable a from 1 to 3, and the other thread keeps testing a = = 1 & & A = = 2 & & A = = 3 Normally, a continuous "success" stream is printed on the console
(note that if you add an else {system. Out. Println ("failure");} Clause, you will find that the test fails far more than it succeeds.)
In practice, it can also work without being declared volatile, but only 21 times on my MacBook If there is no volatile, the compiler or hotspot is allowed to cache or replace if statements with if (false) Most likely, hotspot will start after a period of time and compile it into assembly instructions, which will cache the value of A Volatile, it always keeps printing "successful"
public class VolatileRace { private volatile int a; public void start() { new Thread(this::test).start(); new Thread(this::change).start(); } public void test() { while (true) { if (a == 1 && a == 2 && a == 3) { System.out.println("Success"); } } } public void change() { while (true) { for (int i = 1; i < 4; i++) { a = i; } } } public static void main(String[] args) { new VolatileRace().start(); } }