synchronized 修饰普通方法相当于
synchronized(this){
// 操作
}
synchronized 修饰静态方法
synchronized(C.class){
// 操作
}
非线程安全举例
public class ApplicationDemo08 {
public static void main(String[] args) throws InterruptedException {
Thread thread;
Runnable t;
for(int j = 0; j < 100; j++){
long start = System.currentTimeMillis();
// i 的最大值,代表启动线程数
for(int i = 0; i < 100; i++){
t = new C();
thread = new Thread(t);
thread.start();
}
long end = System.currentTimeMillis();
System.out.println("时间: " + (end - start));
Thread.sleep(500);
System.out.println("----" + C.count);
C.count = 0;
}
}
}
class C implements Runnable{
public static int count = 0;
// 线程不安全情况
public synchronized void add(){
count ++;
}
// 线程安全情况
// public synchronized static void add(){
// count ++;
// }
@Override
public void run() {
this.add();
}
}
打印结果:(线程创建数自己修改测试)