多個線程多個鎖

/**
 * 關鍵字synchronized取得的鎖都是對象鎖!!!!!而不是把一段代碼(方法)當作鎖,
 * 因此代碼中哪一個線程先執行synchronized關鍵字的方法,哪一個線程就持有該方法所屬對象的鎖(Lock),
 * 在靜態方法上加synchronized關鍵字,表示鎖定.class類,類一級別的鎖(獨佔.class類)。
 */
public class MultiThread {
    private int num = 0;
    public synchronized void printNum(String tag){
        try {
            if(tag.equals("a")){
                num = 100;
                System.out.println("tag a, set num over!");
                Thread.sleep(1000);
            } else {
                num = 200;
                System.out.println("tag b, set num over!");
            }
            System.out.println("tag " + tag + ", num = " + num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //注意觀察run方法輸出順序
    public static void main(String[] args) {
        //倆個不一樣的對象
        final MultiThread m1 = new MultiThread();
        final MultiThread m2 = new MultiThread();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                m1.printNum("a");
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override 
            public void run() {
                m2.printNum("b");
            }
        });        
        t1.start();
        t2.start();
    }
}
/**
 * 輸出:tag a, set num over!
        tag b, set num over!
        tag b, num = 200
        tag a, num = 100
 */
/**
 * 關鍵字synchronized取得的鎖都是對象鎖!!!!!而不是把一段代碼(方法)當作鎖,
 * 因此代碼中哪一個線程先執行synchronized關鍵字的方法,哪一個線程就持有該方法所屬對象的鎖(Lock),
 * 在靜態方法上加synchronized關鍵字,表示鎖定.class類,類一級別的鎖(獨佔.class類)。
 */
public class MultiThread {
    private static int num = 0;
    public synchronized static void printNum(String tag){
        try {
            if(tag.equals("a")){
                num = 100;
                System.out.println("tag a, set num over!");
                Thread.sleep(1000);
            } else {
                num = 200;
                System.out.println("tag b, set num over!");
            }
            System.out.println("tag " + tag + ", num = " + num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //注意觀察run方法輸出順序
    public static void main(String[] args) {
        //倆個不一樣的對象
        final MultiThread m1 = new MultiThread();
        final MultiThread m2 = new MultiThread();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                m1.printNum("a");
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override 
            public void run() {
                m2.printNum("b");
            }
        });        
        t1.start();
        t2.start();
    }
}
/**
 * 輸出:tag a, set num over!
        tag a, num = 100
        tag b, set num over!
        tag b, num = 200
 */
相關文章
相關標籤/搜索