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

亡梦爱人 提交于 2020-03-05 11:54:23
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 + "个调用我的");    
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!