日期:2014-05-20  浏览次数:20680 次

一道关于多线程的问题,请高手回答,谢谢!
为Thread撰写两个子类,其中一个的run()在启动后取得第二个Thread object reference,然后调用wait()。另一个子类的run()在过了数秒之后调用notifyAll(),唤醒第一个线程,使第一个线程可以印出消息。

------解决方案--------------------
有点意思,不过其实很简单:

Java code

public class ThreadWaitNotify {

    public static void main(String[] args) throws Exception {
        Thread t = new Thread(){
            public void run() {
                
                try {
                    System.out.println("Thread sleep.....");
                    Thread.sleep(2 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("NotifyAll!");
                synchronized (this) {
                    this.notifyAll();
                }
            }
        };
        
        t.start();
        System.out.println("I am waiting.");
        synchronized (t) {
            t.wait();
        }
        System.out.println("Awaken.");
    }

}

------解决方案--------------------
main也是个线程嘛,帮1楼的改下。
Java code


public class Test04
{
    public static void main(String[] args)
    {
        Thread2 thread2 = new Thread2();
        
        Thread1 thread1 = new Thread1(thread2);

        thread2.start();

        thread1.start();

    }
}

class Thread1 extends Thread
{
    private Thread2 thread2;

    public Thread1(Thread2 thread2)
    {
        this.thread2 = thread2;
    }

    public void run()
    {
        try
        {
            synchronized (thread2)
            {
                System.out.println("thread2 wait.");
                thread2.wait();
            }
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        
        System.out.println("thread2 wakeup.");
    }
}


class Thread2 extends Thread
{
    public void run()
    {
        try
        {
            Thread.sleep(2000);
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        synchronized (this)
        {
            this.notifyAll();
        }
    }
}