package thead.safe.safe4;

public class SynchronizedMethodLocakObject {

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

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

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

    // 对象
    public static class MyObject {
        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();
            }
        }
    }

    // 线程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.methodA();
        }
    }
}
