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

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 + "个调用我的");    
    }
}

 

posted @ 2020-03-05 11:22  yxfyg  阅读(395)  评论(0)    收藏  举报