偶然的想法:测试static块在多线程环境下是否也只能够执行一次
package com.study.thread;
/**
* 测试多线程同步下是否出现同时访问一个静态类的static块
* @author CrazyPig
*
*/
public class ThreadSyn {
private static int count = 0;
static {
System.out.println("start static block");
try {
Thread.sleep(5000);
} catch(InterruptedException e) {
System.out.println("线程中断异常");
}
count ++;
System.out.println("end static block");
}
public static void print() {
System.out.println("count = " + count);
}
public void print0() {
System.out.println("print0()");
}
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// 确保调用static
ThreadSyn.print();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
ThreadSyn newInstance = new ThreadSyn();
newInstance.print0();
}
});
t1.start();
t2.start();
}
}
通过测试结果,证明类的static块在多线程环境下也只能够执行一次,由JVM来保证这一点