码迷,mamicode.com
首页 > 编程语言 > 详细

001JAVA多线程实例对象锁与类锁

时间:2019-03-27 12:33:39      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:vat   try   syn   影响   and   cep   generate   eth   zed   

package com.skcc.mthread;

public class MuiltThread {

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");
}
});

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

}

001JAVA多线程实例对象锁与类锁

标签:vat   try   syn   影响   and   cep   generate   eth   zed   

原文地址:https://blog.51cto.com/6000734/2369767

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!