我理解的同步静态对象是一个变量,如果一个线程正在访问它,其他线程就不能。
class T3
{
static Integer i = 0;
static void callStatic()
{
synchronized(T3.class)
{
System.out.println(i++);
while(true);
}
}
public void notStatic()
{
System.out.println(i++);
while(true);
}
}
class T2 implements Runnable
{
public void run()
{
System.out.println("calling nonstatic");
new T3().notStatic();
}
}
class T implements Runnable
{
public void run()
{
System.out.println("calling static");
T3.callStatic();
}
}
public class Test
{
public static void main(String[] args)
{
new Thread(new T()).start();
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
}
new Thread(new T2()).start();
}
}
但是这个演示程序的输出为:
calling static
0
calling nonstatic
1
我的理解有误吗?或者我错过了什么?
我尝试同步 callStatic
方法,并同步 T3.class
类对象。但没有一个像我想象的那样起作用。
注意:我认为,1 不会被打印,因为 callStatic 已锁定变量 i 并且处于无限循环中。
最佳答案
您不对变量进行同步,而是对对象进行同步。
callStatic
在 1
上同步,然后将 i
设置为 2
。如果 notStatic
此时进入 synchronized(i)
block ,它将在 2
上同步。没有其他线程锁定 2
,因此继续进行。
(实际上,1
和2
不是对象,而是Integer.valueOf(1)
和Integer.valueOf( 2)
返回对象,编译器会自动插入 Integer.valueOf
调用以将 int
转换为 Integer
)
在您的代码中,notStatic
实际上根本不同步。确实,在特定时间只有一个线程可以处于特定对象的同步块(synchronized block)中,但这对不尝试进入同步块(synchronized block)的其他线程没有影响> 阻止。
关于java - 同步静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23404995/