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();
}
}
打印結果:(線程創建數自己修改測試)