E
E
Ernest Farukshin2019-05-09 17:28:33
Java
Ernest Farukshin, 2019-05-09 17:28:33

Is it always necessary to use volatile in multi-threading when working with shared data?

While I was studying multithreading, I noticed that I forgot volatile in this code:

public class Test {
    static int j = 0;
    public static void main(String[] args){
        th Th = new th();
        Thread thread = new Thread(Th);
        thread.start();

        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(j);
    }

    public static class th implements Runnable{
        public void run(){
            for (int i = 0; i < 1000; i++) {
                j++;
            }
        }
    }
}

and wondered when to use volatile and when you can not use it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-05-09
@Ernest3

Where to use volataile?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question