In general, there is an example c in lecture 17
volatile
, it says that if a variable isCancel
is 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 run
the name of the thread and the value are displayed isCancel
and it turned out that regardless depending on whether the variable is present volatile
or 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 volatile
confused and can’t apply it in any way. Maybe I created the example wrong somehow? I also tried to create a class Clock
and inherit from Thread
, and main
create two instances and run both, it also volatile
didn’t work, help me, otherwise I’ll go crazy)
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();
}
}
}
}
GO TO FULL VERSION