線程安全

1.線程安全產(chǎn)生的原因

如果有多個線程在同時運(yùn)行,而這些線程可能會同時運(yùn)行這段代碼。
程序每次運(yùn)行結(jié)果和單線程運(yùn)行的結(jié)果是一樣的,而且其他的變量的值也和預(yù)期的是一樣的,就是線程安全的。

以電影院賣票為例演示線程安全問題
由三個不同的渠道同時賣100張票

線程任務(wù):

public class MyRunnable implements Runnable {

    // 賣電影票(共享數(shù)據(jù))
    private int ticket = 100;
    public void run() {
        while (true) {
            if (ticket > 0) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "出售第" + ticket-- + "張票");
            }
        }

    }
}



public static void main(String[] args) {
        //創(chuàng)建線程任務(wù)
        MyRunnable mr = new MyRunnable();
        //創(chuàng)建線程
        Thread t0 = new Thread(mr);
        Thread t1 = new Thread(mr);
        Thread t2 = new Thread(mr);
        //執(zhí)行線程
        t0.start();
        t1.start();
        t2.start();
        
    }

此時執(zhí)行代碼會發(fā)現(xiàn)會出現(xiàn)賣第0張和-1張票或者重復(fù)賣同一張票的情況,

原因是某個時間多個線程都執(zhí)行了同一段if語句中的代碼,使得全局變量ticket不準(zhǔn)確(操作的票可能被另一個線程賣掉了)

所以解決這個問題需要在一個線程在執(zhí)行線程任務(wù)時,其他線程不能執(zhí)行;這也就變得和單線程一樣了。

解決方法:
(1)同步代碼塊

public class MyRunnable implements Runnable {

    // 賣電影票(共享數(shù)據(jù))
    private int ticket = 100;
    private Object obj = new Object();// 保證鎖對象的唯一性

    public void run() {

        while (true) {
            synchronized (obj) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "出售第" + ticket-- + "張票");
                }
            }

        }

    }

}

注意:用synchronized(鎖對象){}時, 鎖對象要設(shè)為全局變量保證其唯一性;

(2)同步方法


public class MyRunnable2 implements Runnable {

    // 賣電影票(共享數(shù)據(jù))
    private int ticket = 100;
    public void run() {

        while (true) {
            sale();

        }

    }
    public synchronized void sale() {
        // 隱含的鎖 this
        if (ticket > 0) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "出售第" + ticket-- + "張票");
        }

    }

}

注意:將同步代碼塊封裝成一個方法并用synchronized 修飾,這里不需要指定鎖對象,這里的鎖對象默認(rèn)為本類對象this
若果是靜態(tài)同步方法: 在方法聲明上加上static synchronized

public static synchronized void method(){

可能會產(chǎn)生線程安全問題的代碼

}

靜態(tài)同步方法中的鎖對象是 類名.class

(3)使用lock接口

public class MyRunnable2 implements Runnable {

    // 賣電影票(共享數(shù)據(jù))
    private int ticket = 100;
    private Lock lock = new ReentrantLock();//創(chuàng)建鎖對象

    public void run() {

        while (true) {
            lock.lock();
            if (ticket > 0) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "出售第" + ticket-- + "張票");
            }

            lock.unlock();
        }
    }
}

其實和同步代碼塊差不多 ,在創(chuàng)建所對象時用Lock接口的子類創(chuàng)建,用lock()和unlock()方法將可能出現(xiàn)安全的代碼包起來 鎖的釋放可以手動控制

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容