JavaRush /Java Blog /Random EN /Volatile (example in lecture 17)
dimaMJ
Level 25
Craiova

Volatile (example in lecture 17)

Published in the Random EN group
In general, there is an example c in lecture 17 volatile, it says that if a variable isCancelis not used volatile, then by changing the values ​​of this variable from another thread, the others will not know about it, I rewrote the example, only in the method runthe name of the thread and the value are displayed isCanceland it turned out that regardless depending on whether the variable is present volatileor not, the value still changes for all flows, even if you knock, I’m completely confused; if I figured out the synchronization, then I’m volatileconfused and can’t apply it in any way. Maybe I created the example wrong somehow? I also tried to create a class Clockand inherit from Thread, and maincreate two instances and run both, it also volatiledidn’t work, help me, otherwise I’ll go crazy) Volatile (example in lecture 17) - 1
public static void main(String[] args)
    {
       Clock n = new Clock();

        Thread thread1 = new Thread(n);
        Thread thread2 = new Thread(n);
        thread1.start();
        thread2.start();

        try
        {
            Thread.sleep(3000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        n.cancel();

    }

    public static class Clock implements Runnable
    {
        private volatile boolean isCancel = false;

        public void cancel()
        {
            this.isCancel = true;
        }

        @Override
        public void run()
        {
            while (true)
            {

                try
                {   System.out.println(Thread.currentThread().getName()+" "+isCancel);
                    Thread.sleep(2000);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION