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

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

猜你喜欢

转载自www.cnblogs.com/yxfyg/p/12419145.html