首页 > 编程语言 > 详细

编写程序,观察线程中加锁和不加锁的区别(互斥锁)

时间:2020-03-05 12:55:38      阅读:90      评论:0      收藏:0      [点我收藏+]
public class TestSynchronized implements Runnable{
    
    Timer timer = new Timer();
    
    public static void main(String[] args){
        TestSynchronized syn = new TestSynchronized();
        Thread t1 = new Thread(syn);
        t1.setName("t1");
        Thread t2 = new Thread(syn);
        t2.setName("t2");
        t1.start();
        t2.start();
    }
    
    public void run(){
        timer.show();
    }
    
}

class Timer {
    private static int num = 0;
    
    public synchronized void show(){
        num++;
        try{
            Thread.sleep(1);
        } catch(InterruptedException e){
             e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "是第" + num + "个调用我的");    
    }
}

 

编写程序,观察线程中加锁和不加锁的区别(互斥锁)

原文:https://www.cnblogs.com/yxfyg/p/12419145.html

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