-2
class firstThread extends Helper1
{
        Thread thread_1 = new Thread(new Runnable()
        {
            @Override
            public void run() {
                try {
                    for (int i = 1; i <= 20; i++) {
                        System.out.println("Hello World");
                        Thread.sleep(500);
                        if (i == 10) {
                            Notify();
                            Wait();
                        }                       
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }); 
}
class secondThread extends firstThread 
{
    Thread thread_2 = new Thread(new Runnable()
    {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {   
                Wait();
                for(int i = 1; i<=20; i++)
                {
                    System.out.println("Welcome");
                    Thread.sleep(100);
                }
                Notify();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block 
                e.printStackTrace();
            }
        }
    });
}

class Helper1
{
    public synchronized void Wait() throws InterruptedException
    {
        wait();
    }
    public synchronized void Notify() throws InterruptedException
    {
        notify();
    }
}
public class InheritanceClass {

    public static void main(String[] args)
    {
        Thread f = new Thread(new firstThread().thread_1);
        Thread s = new Thread(new secondThread().thread_2);
        f.start();
        s.start();
    }



}

只有第一个线程有输出。请尝试我的代码。我不知道为什么会这样。第二个线程没有输出,我想是因为第二个线程中的Wait(),我不知道该怎么办。

4

2 回答 2

2

问题在于以下代码:

class Helper1
{
    public synchronized void Wait() throws InterruptedException
    {
        wait();
    }
    public synchronized void Notify() throws InterruptedException
    {
        notify();
    }
}

上面,wait()andnotify()调用等价于this.wait()and this.notify()。但是,thread1thread2是独立的对象,因此它们永远不会通过这种方法进行通信。

为了进行通信,您需要一个共享锁对象。例如:

Object lock = new Object();
firstThread = new firstThread(lock);
secondThread = new secondThread(lock);

和同步,如:

void wait(Object lock) {
    synchronized(lock) {
        lock.wait();
    }
}

void notify(Object lock) {
    synchronized(lock) {
        lock.notify();
    }
}

免责声明:我永远不会亲自这样做,但它确实回答了 OP 的问题。

于 2013-06-07T01:52:00.640 回答
0

这段代码真的很混乱,这使得很难看到潜在的问题。

  • 你不应该用小写字母开始一个类,因为它使它看起来像一个方法/字段名称(例如firstThread)。
  • 我很确定WaitNotify也没有理由这样做synchronized
  • 为什么secondThread继承自firstThread???实际上,你为什么有这两个课程呢?您应该只创建一个匿名内部类Helper1或其他东西。

无论如何,问题是当您调用Notify()thread1 时,它会通知自己,而不是 thread2。

于 2013-06-07T01:51:51.597 回答