首页 > 编程语言 > 详细

多线程锁

时间:2020-03-05 11:07:56      阅读:62      评论:0      收藏:0      [点我收藏+]
public class TestThread6 {
    public static void main(String[] args) throws InterruptedException {
        MyClass mo = new MyClass();
        Prooess p = new Prooess(mo);//同一个对象

        Thread t1 = new Thread(p);
        t1.setName("t1");
        Thread t2 = new Thread(p);
        t2.setName("t2");

        //启动线程
        t1.start();
        Thread.sleep(3000);
        t2.start();
    }
}
class Prooess implements Runnable{
    MyClass mo ;
    public Prooess(MyClass mo){
        this.mo = mo;
    }
    @Override
    public void run() {
        if(Thread.currentThread().getName().equals("t1")) {
            mo.m1();
        }
        if(Thread.currentThread().getName().equals("t2")){
            mo.m2();
         }
    }

}


class MyClass{
    public synchronized void m1(){
        //休眠
        try{
            Thread.sleep(10000);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("m1");
    }
//    public void m2(){//这里没有加锁  不需要等m1执行完直接输出
////        System.out.println("m2");
////    }
    public synchronized   void m2(){//同一把锁
        System.out.println("m2");
    }

}

 

多线程锁

原文:https://www.cnblogs.com/rzkwz/p/12417856.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!