package threaddemo.dataracing;

public class SyncDemo {

    public synchronized static void methodA() {
        System.out.println("enter static method methodA, sleep for 1s");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("leaving methodA");
    }

    public synchronized static void methodB() {
        System.out.println("enter static method methodB, sleep for 1s");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("leaving methodB");
    }

    public synchronized void methodC() {
        System.out.println("enter method methodC, sleep for 1s");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("leaving methodC");
    }

    public void methodD() {
        System.out.println("enter method methodD, sleep for 1s");
        synchronized (SyncDemo.class) {
            System.out.println("start run methodD");
            try {
                Thread.sleep(1000);
            } catch ( InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("leaving methodD");
    }

    public static void main(String[] args) {
        SyncDemo sd = new SyncDemo();
        long start = System.currentTimeMillis();
        Thread t1 = new Thread(SyncDemo::methodA);
        Thread t2 = new Thread(SyncDemo::methodB);
        Thread t3 = new Thread(sd::methodC);
        Thread t4 = new Thread(sd::methodD);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        try {
            t1.join();
            t2.join();
            t3.join();
            t4.join();
            System.out.println(STR."cost: \{System.currentTimeMillis() - start}");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
