使用join()和wait()线程java [英] Using join() vs. wait() thread java

查看:113
本文介绍了使用join()和wait()线程java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一系列线程。他们需要按照以下顺序开始:

I need to make sequence of threads. They need to start in order like this:

A然后是B然后是C,最后是D。

当D完成后,C可以完成B,然后是A。

When D is finished then C can finish then B, then A.

在这种情况下,最好使用 join() threads或 wait()?为什么?

In this situation what is better to use join() threads or wait()? and why?

我的线程需要启动并打印消息你好我是线程a / b / c / d 当他们完成时他们需要打印我已经完成了/ b / c / d

My threads need to start and print the message Hello I'm thread a/b/c/d and when they are finished they need to print I'm finished a/b/c/d.

推荐答案

由于您正在等待其他线程完成(即完成执行), join()将是更好的选择。

Since you are waiting for the 'other' thread to complete (i.e. finish execution), join() would be the better choice.

的javadoc join()简单地说:等待此线程死亡。

这个机制相对简单:

        @Override
        public void run() {
            System.out.println("Hello I'm thread " + getName());
            if (otherThread != null) {
                while (otherThread.isAlive()) {
                    try {
                        otherThread.join();
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
            }
            System.out.println("I'm finished " + getName());
        }

要解释:你需要引用 otherThread 。所以 a 是指 b b 是指 c c d d 不引用任何 otherThread (它为空)。

To explain: you need to have a reference to the otherThread. So a refers to b, b refers to c, c refers to d and d doesn't refer to any otherThread (it's null).

声明 otherThread.join()等待另一个线程完成。它被包装在循环中,因为 join()可以抛出 InterruptedException (虽然很少在实践中)。

The statement otherThread.join() waits for the other thread to complete. It is wrapped in a loop since join() can throw InterruptedException (though rarely in practise).

希望这有帮助,祝你好运。

Hope this helps, good luck.

这篇关于使用join()和wait()线程java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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