multithreading - Java while loop can not detect change by thread -


this question has answer here:

i'm new in java thread, write test program:

//mytest.java

public class mytest{     public static void main(string[] args){         mythread thread = new mythread();         int n;          thread.start();          while (true){             //system.out.print("");              n = mythread.num;             if (n != 0){                 system.out.println("<num> has been modified " + n);                 if (n == -1) break;                  mythread.num = 0;             }         }          system.out.println("main thread terminated!");     } } 

//mythread.java

public class mythread extends thread {     public static int num = 0;      public void run(){         java.util.scanner input = new java.util.scanner(system.in);         int n;          while (true){             system.out.print("type number: ");             n = input.nextint();             if (n == -1) break;             num = n;         }          input.close();         system.out.println("mythread thread terminated!");     } } 

when run this, show message: "type number: " , input number. then, while loop on main class can not detect mythread.num has been modified. prompt message, , on... type -1, second thread terminated, main thread doesn't show message , never terminated.

i try fix add code system.out.print("") below while(true) (as marked comment above). work when type -1, still can not detect.

i'm don't know why command system.out.print("") can make work(but not solution) , problem code. how can fix it?

this because static int num not marked volatile. java "knows" num not going change after first read, not reading again.

change declaration to

static volatile int num; 

to fix problem. force memory reads on each access num.

note: static variables not way of communicating between threads.


Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -