package thead.safe.safe4;

public class SynchronizedMethodLocakObject2 {

    public static void main(String[] args) {
        MyObject myObject = new MyObject();

        ThreadA threadA = new ThreadA(myObject);
        threadA.setName("ThreadA");

        ThreadB threadB = new ThreadB(myObject);
        threadB.setName("ThreadB");

        threadA.start();
        threadB.start();
    }

    // 测试对象
    public static class MyObject {

        /**
         * 测试方法A
         */
        synchronized public void methodA() {
            try {
                System.out.println(Thread.currentThread().getName() + " 开始 " + System.currentTimeMillis());
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + " 结束 " + System.currentTimeMillis());
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        /**
         * 测试方法B
         * 如果不加synchronized，整个程序是异步执行的
         * 如果加synchronized，整个程序是同步执行的
         */
        synchronized public void methodB() {
            try {
                System.out.println(Thread.currentThread().getName() + " 开始 " + System.currentTimeMillis());
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + " 结束 " + System.currentTimeMillis());
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }

    // 线程A
    public static class ThreadA extends Thread {

        private final MyObject myObject;

        public ThreadA(MyObject myObject) {
            super();
            this.myObject = myObject;
        }

        @Override
        public void run() {
            super.run();
            myObject.methodA();
        }
    }

    // 线程B
    public static class ThreadB extends Thread {

        private final MyObject myObject;

        public ThreadB(MyObject myObject) {
            super();
            this.myObject = myObject;
        }

        @Override
        public void run() {
            super.run();
            myObject.methodB();
        }
    }
}
