synchronized类锁代码示例

在static方法中,synchronized(XX.class){...}

public class PrintFruit {
    public static void printA(){
        System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date())+" Apple");
    }

    public static void printB(){
        System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date())+" Banana");

    }
}

public class SyncTest {
    public static void main(String[] args) {
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                synchronized (PrintFruit.class) {
                    PrintFruit.printA();
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread t1 = new Thread(r1, "t1");
        Thread t2 = new Thread(r1,"t2");
        Thread t3 = new Thread(r1, "t3");

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                synchronized (PrintFruit.class) {
                    PrintFruit.printB();
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread t4 = new Thread(r2, "t4");
        Thread t5 = new Thread(r2, "t5");
        Thread t6 = new Thread(r2, "t6");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
    }
}

运行结果:
synchronized类锁代码示例

上一篇:阿里后台四年,想要跳槽字节,艰难4面,已收开发岗offer


下一篇:volatile和synchronized的区别