其他分享
首页 > 其他分享> > synchronized类锁代码示例

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,Thread,示例,void,start,类锁,new,public,PrintFruit
来源: https://blog.csdn.net/zhangjin1120/article/details/120665687