避免等待终止线程 [英] Avoid waiting for a terminated thread

查看:148
本文介绍了避免等待终止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是,在我打电话给 wait()之前,有时我已经开始完成一个线程。这似乎导致我的程序等待不会再发生的事情( notify())。我怎样才能确保不等待完成的线程?

I'm having the problem that sometimes a thread that I've started finishes before I call wait() on it. It seems that this causes my program to wait for something that is not going to happen again (notify()). How can I make sure not to wait for a finished thread?

void someFunction() {

  MyThread thread = new MyThread();

  thread.start();

  // .. some stuff that takes sometimes quite long

  synchronized(thread) {
    try {
      thread.wait();
    } catch(InterruptedException e) {
      // ..
    }
  }
}


推荐答案

如果您阅读了线程的JavaDocs,它会告诉您从未使用在线程对象上等待,通知或notifyAll 。你应该使用join()

If you read the JavaDocs for Thread, it tells you NEVER EVER use wait, notify, or notifyAll on Thread objects. You should use join()

这篇关于避免等待终止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆