問題描述使用繼承Thread方法創(chuàng)建線程實例重寫run()方法的時候,用synchronized關(guān)鍵字修飾run()方法結(jié)果是線程之間不是同步進(jìn)行,計算結(jié)果出現(xiàn)問題代碼片段public class MyThreadDemo9 extends Thread{ private static int count = 0; public String status; public MyThreadDemo9(String status){ this.status = status;
} @Override
public synchronized void run() { for(int i = 0; i < 100; i++) {
count++;
}
} public static void main(String[] args) throws InterruptedException { for(int i = 0; i < 100; i++) {
MyThreadDemo9 m8 = new MyThreadDemo9("Thread status - " + i);
m8.start();
}
Thread.sleep(3000);
System.out.println(MyThreadDemo9.count);
}
}這個是什么原因呢,不能使用 synchronized 關(guān)鍵字修飾run()方法嗎
1 回答

慕雪6442864
TA貢獻(xiàn)1812條經(jīng)驗 獲得超5個贊
你這里加鎖的是每個線程對象本身,其實并沒有并發(fā)控制。這里用AtomicInteger就可以實現(xiàn)線程安全的增加
添加回答
舉報
0/150
提交
取消