java線程--object.wait&&object.notify

object.wait&&object.notify

public class Test {

    final static Object obj = new Object();

    static class T1 extends Thread {

        @Override
        public void run() {

            synchronized (obj) {
                System.out.println(System.currentTimeMillis() + " t1 start && wait");
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis() + " t1 end");
            }
        }
    }

    static class T2 extends Thread {

        @Override
        public void run() {

            synchronized (obj) {
                System.out.println(System.currentTimeMillis() + " t2 start && notify");
                obj.notify();

                System.out.println(System.currentTimeMillis() + " t2 end");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        T1 t1 = new T1();
        T2 t2 = new T2();
        t1.start();
        t2.start();
    }
}

synchronized 得到對象的監視器

thread

相關文章
相關標籤/搜索