0

this is my test code

public class Test {
    public static void main(String[] args) {
        Data data = new Data();
        Thread t1 = new Thread(new Print(data));
        t1.setName("Print");
        Thread t2 = new Thread(new Update(data));
        t2.setName("Update");
        t2.start();
        t1.start();
    }
    private static class Data {
        private String number = "0";
        public String getNumber() {
            return number;
        }
        public void setNumber(String number) {
            this.number = number;
        }
    }
    private static class Update implements Runnable {
        private Data data;
        public Update(Data data) {
            this.data = data;
        }
        @Override
        public void run() {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                String number = String.valueOf(i);
                data.setNumber(number);
                if (number.equals("100000")) {
                    System.out.println("|" + System.currentTimeMillis() + "|");
                    break;
                }
            }
            System.out.println("update finish");
        }
    }
    private static class Print implements Runnable {
        private Data data;
        public Print(Data data) {
            this.data = data;
        }
        public Data getData() {
            return data;
        }
        @Override
        public void run() {
            while (true) {
                if (data.getNumber().equals("100000")) {
                    System.out.println("#" + System.currentTimeMillis() + "#");
                    break;
                }
            }
        }
    }}

I want to update the filed number and when equals 100000 print it.but the Print task was blocked when i run this code, and when I define the number as volatile it runs well. I don't understand why..., anyone can help me?

arron
  • 5
  • 3
  • 1
    Without `volatile` or `synchronized` you have no guarantees that the threads will see each-others updates. – Thilo May 11 '16 at 10:07
  • With out `volatile` each thread is free to take a local copy of the data for performance reason. When this happens, there is no guarantee one thread will ever see than changes of another thread. – Peter Lawrey May 11 '16 at 10:10

0 Answers0