1. 程式人生 > 其它 >【java多執行緒】(四)執行緒併發問題

【java多執行緒】(四)執行緒併發問題

技術標籤:java基礎篇多執行緒java併發程式設計thread

public class Station implements Runnable{

    static int ticket = 10;
    boolean flag = true;

    public static void main(String[] args) {
        Station station = new Station();

        new Thread(station,"張三").start();
        new Thread(station,"李四"
).start(); new Thread(station,"王五").start(); } public void run() { while (flag){ buyTicket(); try { Thread.sleep(200); }catch (InterruptedException e){ e.printStackTrace(); } } }
void buyTicket(){ if (ticket>0){ System.out.println(Thread.currentThread().getName() + "買了第" + ticket + "票"); ticket--; }else { System.out.println("票賣光了"); flag = false; } } }

在這裡插入圖片描述

同一張票被三個人買走,三個執行緒操控同一資源

加鎖(synchronized)

public class StationTest implements Runnable{

    static int ticket = 10;
    boolean flag = true;
    private Object object="obj";

    public static void main(String[] args) {
        StationTest stationTest = new StationTest();

        new Thread(stationTest,"張三").start();
        new Thread(stationTest,"李四").start();
        new Thread(stationTest,"王五").start();

    }
    public void run() {
        while (flag){
            buyTicket();
            try {
                Thread.sleep(200);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    void buyTicket(){
        synchronized (object){
            if (ticket>0){
                System.out.println(Thread.currentThread().getName() + "買了第" + ticket + "票");
                ticket--;
            }else {
                flag = false;
                System.out.println("票賣光了");
            }
        }
    }
}

在這裡插入圖片描述

問題

這裡理解為加鎖之後只能允許一個執行緒執行這個程式碼
那synchronized裡面加鎖的物件為什麼可以是隨意的物件?
要鎖方法還是鎖物件的區別?

synchronized加鎖不管是加在方法上還是直接加在一個物件上synchronized(this或者obj),一個物件只能加上一個鎖,加在方法上表示,多個執行緒中run()方法如果呼叫執行了這個加鎖的方法,那麼在同一時刻只能有一個執行緒來訪問這個方法。
如果直接synchronize(this或者obj)就表示多個執行緒想使用this物件或者obj物件中的方法或者變數,那麼同一時刻只能有一個執行緒能夠獲得synchronized這個鎖,並且進入此物件執行物件中的方法或者改變變數。