1

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?

phibao37
  • 2,230
  • 4
  • 26
  • 35

2 Answers2

2

This is because static int num is not marked volatile. Java "knows" that num is not going to change after the first read, so it is not reading it again.

Change the declaration to

static volatile int num;

to fix this problem. This will force memory reads on each access to num.

Note: static variables are not a good way of communicating between threads.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

As for the problew with detecting -1, your break statement prevents it. You should break out of the loop after updating num.

Zoyd
  • 3,449
  • 1
  • 18
  • 27