/**
* 测试 static 块是不是同步的
*/
public class TestIfStaticBlockIsAlwaysSynchronized {
// 创建多个线程,它们几乎同时创建 TestClass 对象。
public static void main(String[] args) {
new CreateTestClassThread().start();
new CreateTestClassThread().start();
new CreateTestClassThread().start();
new CreateTestClassThread().start();
}
// 创建 TestClass 对象的线程
static class CreateTestClassThread extends Thread {
@Override
public void run() {
new TestClass();
}
}
}
class TestClass {
public static final Object lock = new Object();
// static 块只会执行一次。当一个线程进入时,其他线程会等待该线程执行完,然后跳过。
static {
try {
System.out.printf("Thread %d enters static block.n",
Thread.currentThread().hashCode());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 构造函数,每个线程都会执行一次。
TestClass() {
System.out.printf("TestClass object created in thread %dn",
Thread.currentThread().hashCode());
}
}
执行结果:
Thread 6927154 enters static block. -- 后面等了两秒才继续输出
TestClass object created in thread 3043939
TestClass object created in thread 6927154
TestClass object created in thread 22540508
TestClass object created in thread 3043939
果然如此,static 块本身是同步的。
:D