I'm new in java thread, I write a 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 to " + 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 a number: ");
n = input.nextInt();
if (n == -1) break;
num = n;
}
input.close();
System.out.println("MyThread thread terminated!");
}
}
When I run this, It show a message: "Type a number: " and I input some number. But then, the while loop on main class can not detect the MyThread.num
has been modified.
So it prompt a message, and so on... Even I type -1, the second thread terminated, but the main thread doesn't show any message and never terminated.
I try to fix by add a code System.out.print("")
below the while(true)
(as I marked a comment above). Then It work but when type -1, it still can not detect.
I'm don't know why the command System.out.print("") can make it work(but not a good solution) and what is problem with my code. How can I fix it?