首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

一道关于多线程的有关问题,请高手回答,多谢

2012-08-09 
一道关于多线程的问题,请高手回答,谢谢!为Thread撰写两个子类,其中一个的run()在启动后取得第二个Thread o

一道关于多线程的问题,请高手回答,谢谢!
为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();        }    }} 

热点排行