线程并发 wait() 其他线程完成并继续其工作
我想让一个线程等待另一个线程完成,而不是终止它,启动第二个线程并创建第一个线程的另一个实例。这样做是正确的吗?
Thread1 first = new Thread1();
first.start();
while(flag==true){//start while1
first.wait();
Thread2 second = new Thread2();
second.start();
while(second.isAlive()){
Toast toast = new Toast(...WORKING IN PROGRESS...);//just show something
}
flag = false;
}//end of while1
第一个线程会等到第二个线程停止运行吗?我只希望第一个线程暂停并在第二个线程完成运行后继续工作。感谢您的帮助
I want to make a thread to wait for another to finish,instead to terminate it,start the second and create another instance of the firt thread.It's right doing so?
Thread1 first = new Thread1();
first.start();
while(flag==true){//start while1
first.wait();
Thread2 second = new Thread2();
second.start();
while(second.isAlive()){
Toast toast = new Toast(...WORKING IN PROGRESS...);//just show something
}
flag = false;
}//end of while1
Will the Thread first wait untill the Thread second will stop to run?? I just want Thread first paused and continue working after thread second has finished to run. Thanks for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您正在编写 Java,则可以使用 Thread.join() 方法强制某个线程等待另一个线程结束。例如,如果您希望线程 1 等待线程 2 完成:
注意:代码中的 wait 命令将导致运行的线程(在本例中不是线程 1 或线程 2,而是创建它们的线程)等待() [第4行],那就去睡觉吧。具体来说,只有当另一个线程(thread1或thread2)调用first.notify()时,等待的线程才能被唤醒。否则,您上面提供的代码将永远不会超过第 4 行。
Assuming that you're writing Java, you can use the Thread.join() method to force some thread to wait for another to end. For example, If you want Thread 1 to wait until Thread 2 finishes:
NB: The wait command in your code will cause the thread running (neither thread1 or thread 2 in this case, but the thread that creates them) to wait() [line 4], that is go to sleep. Specifically, the thread waiting can only be woken up if another thread (thread1 or thread2) calls first.notify(). The code you've presented above will never get past line 4 otherwise.
我认为您正在寻找这样的东西:
然后只需将可运行的
Worker
传递到线程中:另请注意,除非您创建一个名为
Worker
和的类Worker2
,那些将不存在。然而,没有什么理由执行一个线程,等待它完成然后执行另一个线程:它完全违背了并发的目的,你还不如按顺序执行代码。I think you're looking for something like this:
Then just pass the runnable
Worker
into the thread:Please also note that unless you make a class called
Worker
andWorker2
, those will not exist. However, there is very little reason to execute one thread, wait for it to finish and then execute another thread: it totally defeats the purpose of concurrency and you might as well just execute the code sequentially.同步线程是完全可能的——我最喜欢的方法之一是使用 CountdownLatch ——但是您的代码显示出对如何使用它们缺乏了解。我建议在继续之前先阅读更多关于线程的知识。如果你做错了,线程和并发很容易搞砸。
It's entirely possible to synchronize threads -- one of my favorite ways is with a
CountdownLatch
-- but your code shows a lack of understanding of how to use them. I'd suggest reading up a bit more on Threads in general before moving forward. Threads and concurrency are very easy to screw up royally if you do it wrong.