繁体   English   中英

在调用wait和notify之后,我尝试从主线程加入两个线程

[英]I try to join two threads from the main thread, after calling wait and notify

首先,我尝试定义一个包含2个同步方法的类,第一个包含一个wait()调用,第二个包含notify()调用。

 class Xa {
 public synchronized void printX() {
    try {
        wait();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("XXX");
}

public synchronized void notifyX() {
    System.out.println("111");
    notify();
}
}

然后,我尝试在主线程中创建两个线程,第一个线程调用Xa类的对象的printX()方法,第二个线程调用同一对象的notifyX()方法,最后主线程加入两个线程。

我用for循环重复这种情况

public class TryQ {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Thread t1 = null;
    Thread t2 = null;
    for(int i=1 ; i<=100; i++) {
        Xa x = new Xa();

        t1 = new Thread() {
            @Override
            public void run() {
                x.printX();
            }
        };

        t2 = new Thread() {
            @Override
            public void run() {
                x.notifyX();
            }
        };

        t1.start();
        t2.start();

        try {
            t1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            t2.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }       
}
}

问题是,在没有连接的情况下,第一个和第二个线程都准确地打印了100次,但是当我尝试通过主线程将它们连接时,我最多只能输出2或3行...并且程序仍在运行!

为什么?

无论是否使用join存在问题。

问题是,如果t2首先执行notifyX

public synchronized void notifyX() {
    System.out.println("111");
    notify();
}

然后t1调用printXt1将永远被阻塞!

public synchronized void printX() {
    try {
        wait();   <--- since t2 has finished, t1 will get stuck here!
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("XXX");
}

区别在于:

  • 如果没有join ,尽管第一个t1被卡住,主线程将创建一个新的t1并运行。
  • 使用join ,因为第一个t1卡住了,所以join将阻塞主线程,因此不会有下一代。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM