關(guān)于Java語言中的線程安全問題
Java語言是一種支持多線程的語言,它通過同步(互斥)和協(xié)作(等待和喚醒)來完成。這里聊聊同步。
線程不安全主要來自于類變量(靜態(tài)變量)和實(shí)例變量,前者位于方法區(qū)中,后者位于堆中,都是共享區(qū)域。局部變量是沒有這個問題的,因?yàn)樗诰€程獨(dú)有的棧中。先看下面的例子:
- public class Test implements Runnable {
- private int j;
- public Test() {
- }
- public void testThreadLocal() {
- System.out.println(Thread.currentThread().getId()
- + ":============================= begin");
- j = 2;
- System.out.println(Thread.currentThread().getId() + ":" + j);
- j = 20;
- System.out.println(":" + j * 3 + ":");
- System.out.println(Thread.currentThread().getId()
- + ":============================= end");
- }
- public static void main(String[] args) {
- Test t = new Test();
- for (int i = 0; i < 3000; i++) {
- new Thread(t).start();
- }
- }
- @Override
- public void run() {
- testThreadLocal();
- }
- }
執(zhí)行這個類的main方法,會出現(xiàn)線程不安全的問題。上面藍(lán)色的語句,應(yīng)該打印出:60:,但實(shí)際開了3000個線程(為了方便出現(xiàn)不安全的現(xiàn)象)后,會出現(xiàn)下面紅色的:6:
655:============================= end
49:============================= end
:6:
156:============================= end
152:2
:60:
修改main方法,用多個Test對象,結(jié)果也是一樣。
- public static void main(String[] args) {
- Test t = new Test();
- for (int i = 0; i < 3000; i++) {
- new Thread(new Test() ).start();
- }
- }
我們保留多個Test對象的做法,在testThreadLocal方法上加一個同步關(guān)鍵字。
- public synchronized void testThreadLocal()
結(jié)果沒有用,仍然是不安全的。改成一個Test對象,這下可以了。原因很簡單,synchronized通過在對象上加鎖來實(shí)現(xiàn)線程安全。當(dāng)使用多個Test對象時(shí),僅僅在this對象上加鎖是不行的,要在類(在java中,類仍然通過一個特殊的Class對象來體現(xiàn))上加鎖才行。所以改成:
- public void testThreadLocal() {
- synchronized (this.getClass()) {
- System.out.println(Thread.currentThread().getId()
- + ":============================= begin");
- j = 2;
- System.out.println(Thread.currentThread().getId() + ":" + j);
- j = 20;
- System.out.println(":" + j * 3 + ":");
- System.out.println(Thread.currentThread().getId()
- + ":============================= end");
- }
- }
這下可以了。我們再看使用類變量的情況,先把synchronized關(guān)鍵字去掉,恢復(fù)到最初的代碼,然后把實(shí)例變量改成類變量。
- private int j;
- private static int j;
實(shí)驗(yàn)結(jié)果和使用實(shí)例變量基本相同,***的不同之處在于,我們可以這樣在類上加鎖了,注意,testThreadLocal方法被改成靜態(tài)方法。
- public synchronized static void testThreadLocal() {
- System.out.println(Thread.currentThread().getId()
- + ":============================= begin");
- j = 2;
- System.out.println(Thread.currentThread().getId() + ":" + j);
- j = 20;
- System.out.println(":" + j * 3 + ":");
- System.out.println(Thread.currentThread().getId()
- + ":============================= end");
- }
從上面的例子看到,我們使用類變量和實(shí)例變量的時(shí)候,都要非常小心,在多線程的環(huán)境下,很容易出現(xiàn)線程不安全的情況。上面我們還僅僅以基本類型int為例,如果是其他復(fù)雜類型,甚至像long這種在賦值時(shí)要兩次原子操作的基本數(shù)據(jù)類型,線程不安全的情況還要隱秘一些。
編輯推薦】