001JAVA多線程實例對象鎖與類鎖

package com.skcc.mthread;ide

public class MuiltThread {ui

private static int num = 0;

public MuiltThread() {
    // TODO Auto-generated constructor stub
}

/****
 *   synchronized void printNum(String tag)  表明 synchronized鎖定的MuiltThread實例對象鎖(m1,m2二者間互不影響)
 *   static  synchronized void printNum(String tag) 表明synchronized 競爭的是MuiltThread類鎖 
 * 
 * ****/
public static  synchronized void printNum(String tag) {
    try {
        if(tag.equals("a")) {
            num = 100;
            System.out.println("tag a,num 100 set over.");
            //Thread.sleep(1000);
        }
        else {
            num=200;
            System.out.println("tag b,num 200 set over.");
        }
        System.out.println("tag is " + tag + "  num is "+ num);
    } catch (Exception e) {
        // TODO: handle exception
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    MuiltThread m1 = new MuiltThread();
    MuiltThread m2 = new MuiltThread();

    Thread t1 = new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            //m1.printNum("a");
            MuiltThread.printNum("a");
        }
    });

    Thread t2 = new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub

// m2.printNum("b");
MuiltThread.printNum("b");
}
});code

t1.start();
    t2.start();
}

}對象

相關文章
相關標籤/搜索