简体   繁体   中英

Test volatile variable in java

I wrote a simple program to test volatile variables. As for the program I have written when t2 runs, it should pick value of i as 3 and should never go inside the while loop

but it outputs 0 1 2 0 1 2 since it is volatile shouldnt it print just 0,1,2 ??

public class Test{
     public static void main(String []args) throws InterruptedException{      
          TestVolatile t1 = new TestVolatile();
          t1.start();
          t1.join();
          TestVolatile t2 = new TestVolatile();
          t2.start();  
     }
}

class TestVolatile extends Thread{
    volatile int i = 0;  
    public void run(){
        while(i < 3){
            System.out.println(i);
            i++;
        }
    }   
}

You are creating 2 different TestVolatile objects and each of them has its own variable i and works only with it. So first object increments and outputs 0, 1, 2 and so does the second.

You need tomake i static like this

static volatile int i = 0; 

Since 2 threads are accessing 2 copies of the i variable you got the output.

Make the i variable static -

static volatile int i = 0;

For more info - https://www.javacodegeeks.com/2018/03/volatile-java-works-example-volatile-keyword-java.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM