public class Mutex {
private int val;
public Mutex(int val) {
this.val=val;
}
public int getVal() {
return val;
}
public void printVal()
{
int i=0;
while (true)
{
System.out.println(Thread.currentThread().getName()+" "+this.getVal());
if(i==50)
break;
else
i++;
}
}
public static void main(String args[])
{
final Mutex m1=new Mutex(1);
final Mutex m2 = new Mutex(2);
new Thread(new Runnable()
{
@Override
public void run() {
m1.printVal();
}
},"THREAD-1").start();
new Thread(new Runnable()
{
@Override
public void run() {
m2.printVal();
}
},"THREAD-2").start();
}
}
当“val”的类型为“int”时,THREAD-1 和 THREAD-2 不会交错,而如果我将其类型更改为 double,则线程会交错。我了解原语是线程安全的(long 和 double 除外)。考虑到上述代码示例,这究竟是如何工作的?