Java代码:一个线程在继续之前等待另一个线程完成 [英] Java Code: A thread waits for another thread to finish before continuing

查看:138
本文介绍了Java代码:一个线程在继续之前等待另一个线程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个程序,其中我有2个线程。

线程A执行某些操作并向线程B发送结果。

线程A等待线程B的响应在处理另一项任务之前。



我该怎么做?

有人能给我一个示例代码吗?

谢谢!

I am creating a program wherein I have 2 threads.
Thread A performs something and sends to Thread B the result.
Thread A waits for response from Thread B before processing another task.

How can I do this?
Can anyone give me a sample code?
thanks!

推荐答案

如果你想等待上一个线程完成,在你开始下一个线程之前,你需要在两者之间添加thread.join(): />


例如: -



If you want to wait for the previous thread to finish, before you start the next, you add thread.join() in between:

for eg:-

for(int i = 0; i < 10; i++) {
    thread = new Thread(this);
    thread.start();

    thread.join();    // Wait for it to finish.
}


你必须将你的线程分配给一个变量,然后在这个变量上调用 join(),如:

You have to assign your thread to a variable and later call join() on this variable like:
Thread t = new Thread() {
    public void run() {
        System.out.println("text");
        // other complex code
    }
 };
 t.start();
 t.join();



这样你就会等到线程结束然后再继续。


This way you will wait until the thread finishes and just then continue.


这篇关于Java代码:一个线程在继续之前等待另一个线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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