What is the volatile keyword useful for?

前端 未结 23 2668
闹比i
闹比i 2020-11-21 05:32

At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.

Given the detail in which that arti

23条回答
  •  无人及你
    2020-11-21 06:01

    Volatile does following.

    1> Read and write of volatile variables by different threads are always from memory, not from thread's own cache or cpu register. So each thread always deals with the latest value. 2> When 2 different threads work with same instance or static variables in heap, one may see other's actions as out of order. See jeremy manson's blog on this. But volatile helps here.

    Following fully running code shows how a number of threads can execute in predefined order and print outputs without using synchronized keyword.

    thread 0 prints 0
    thread 1 prints 1
    thread 2 prints 2
    thread 3 prints 3
    thread 0 prints 0
    thread 1 prints 1
    thread 2 prints 2
    thread 3 prints 3
    thread 0 prints 0
    thread 1 prints 1
    thread 2 prints 2
    thread 3 prints 3
    

    To achieve this we may use the following full fledged running code.

    public class Solution {
        static volatile int counter = 0;
        static int print = 0;
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Thread[] ths = new Thread[4];
            for (int i = 0; i < ths.length; i++) {
                ths[i] = new Thread(new MyRunnable(i, ths.length));
                ths[i].start();
            }
        }
        static class MyRunnable implements Runnable {
            final int thID;
            final int total;
            public MyRunnable(int id, int total) {
                thID = id;
                this.total = total;
            }
            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (true) {
                    if (thID == counter) {
                        System.out.println("thread " + thID + " prints " + print);
                        print++;
                        if (print == total)
                            print = 0;
                        counter++;
                        if (counter == total)
                            counter = 0;
                    } else {
                        try {
                            Thread.sleep(30);
                        } catch (InterruptedException e) {
                            // log it
                        }
                    }
                }
            }
        }
    }
    

    The following github link has a readme, which gives proper explanation. https://github.com/sankar4git/volatile_thread_ordering

提交回复
热议问题