成都创新互联网站制作重庆分公司

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

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多线程实例对象锁与类锁
文章地址:http://cxhlcq.com/article/jdiohs.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部