java多线程_类锁的使用

 

/*
    类锁,类只有一个,所以锁是类级别的,只有一个.
*/
public class ThreadTest17
{
    public static void main(String[] args) throws Exception{
        
        Thread t1 = new Thread(new Processor());
        Thread t2 = new Thread(new Processor());

        t1.setName("t1");
        t2.setName("t2");

        t1.start();
        
        //延迟,保证t1先执行
        Thread.sleep(1000);

        t2.start();

    }
}

class Processor implements Runnable
{
    public void run(){
        
        if("t1".equals(Thread.currentThread().getName())){
            MyClass.m1();
        }

        if("t2".equals(Thread.currentThread().getName())){
            MyClass.m2();
        }
    }
}

class MyClass
{
    //synchronized添加到静态方法上,线程执行此方法的时候会找类锁。
    public synchronized static void m1(){
        
        try{Thread.sleep(10000);}catch(Exception e){}

        System.out.println("m1....");
    }

    //m2方法等m1结束之后才能执行,该方法有synchronized
    //线程执行该代码需要“类锁”,而类锁只有一个。类锁锁定的是该类对应的Class对象
    public synchronized static void m2(){
        System.out.println("m2...");
    }
}

 

转载于:https://www.cnblogs.com/Allen-win/p/7352533.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值