为Thread撰写两个子类,其中一个的run()在启动后取得第二个Thread object reference,然后调用wait()。另一个子类的run()在过了数秒之后调用notifyAll(),唤醒第一个线程,使第一个线程可以印出消息。
这里面的“取得第二个Thread object reference”是什么意思啊,高手能用代码解释下吗

解决方案 »

  1.   

    应该是取得第二个线程对象的引用的意思吧,我也正在学多线程编程。
    public class ThreadTest {

    private Thread child = null; /**
     * @param args
     */
    public static void main(String[] args) {
    ThreadTest test = new ThreadTest();
    test.work();
    }

    public void work() {
    myThread1 thread1 = new myThread1();
    myThread2 thread2 = new myThread2();

    //将第二个线程的引用赋值给成员变量child
    this.child = thread2;

    thread1.start();
    thread2.start();
    }

    class myThread1 extends Thread {

    public void run() {
    synchronized(child) {
    try {
    child.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    System.out.println("我睡醒了,现在开始打印信息");
    }
    }
    }

    class myThread2 extends Thread { public void run() {
    synchronized(this) {
    try {
    sleep(5 * 1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    System.out.println("唤醒另一个线程吧");
    this.notifyAll();
    }
    }

    }}
      

  2.   

    忘记加注释了
    public class ThreadTest {
        
        private Thread child = null;    /**
         * @param args
         */
        public static void main(String[] args) {
            ThreadTest test = new ThreadTest();
            test.work();
        }
        
        public void work() {
            myThread1 thread1 = new myThread1();
            myThread2 thread2 = new myThread2();
            
            //将第二个线程的引用赋值给成员变量child
            this.child = thread2;
            
            thread1.start();
            thread2.start();
        }
        
        class myThread1 extends Thread {
            
            public void run() {
                synchronized(child) {
                    try {
                        //取得第二个Thread object reference,然后调用wait()
                        child.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                    System.out.println("我睡醒了,现在开始打印信息");
                }
            }
        }
        
        class myThread2 extends Thread {        public void run() {
                synchronized(this) {
                    try {
                        sleep(5 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                    System.out.println("唤醒另一个线程吧");
                    this.notifyAll();
                }
            }
            
        }}