问题描述
在这段代码中,两者的连接和分解意味着什么? t1.join()
导致 t2
停止直到 t1
终止?
In this code, what does the two joins and break mean? t1.join()
causes t2
to stop until t1
terminates?
Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread t2 = new Thread(new EventThread("e2"));
t2.start();
while (true) {
try {
t1.join();
t2.join();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
推荐答案
到来自:
To quote from the Thread.join()
method javadocs:
有一个运行你的示例代码的线程可能是。
There is a thread that is running your example code which is probably the main thread.
- 主要线程创建并启动
t1
和t2
线程。两个线程并行开始运行。 - 主线程调用
t1.join()
等待t1
线程完成。 -
t1
线程完成,t1 .join()
方法在主线程中返回。请注意,t1
可能已经在join()
调用之前完成,在这种情况下join()
调用将立即返回。 - 主线程调用
t2.join()
to等待t2
线程完成。 -
t2
线程完成(或者它可能在t1
线程之前完成)并且t2.join()
方法在主线程中返回。
- The main thread creates and starts the
t1
andt2
threads. The two threads start running in parallel. - The main thread calls
t1.join()
to wait for thet1
thread to finish. - The
t1
thread completes and thet1.join()
method returns in the main thread. Note thatt1
could already have finished before thejoin()
call is made in which case thejoin()
call will return immediately. - The main thread calls
t2.join()
to wait for thet2
thread to finish. - The
t2
thread completes (or it might have completed before thet1
thread did) and thet2.join()
method returns in the main thread.
了解 t1
和<$ c $非常重要c> t2 线程一直在运行 ,但启动它们的主线程需要等待它们才能继续运行。这是一种常见的模式。此外, t1
和/或 t2
可能在主线程调用<$>之前完成 join()
就可以了。如果是,那么 join()
将不会等待,但会立即返回。
It is important to understand that the t1
and t2
threads have been running in parallel but the main thread that started them needs to wait for them to finish before it can continue. That's a common pattern. Also, t1
and/or t2
could have finished before the main thread calls join()
on them. If so then join()
will not wait but will return immediately.
否。调用 t1.join()
的 main 线程将停止运行并等待 t1
线程完成。 t2
线程并行运行,不受 t1
或 t1.join的影响()
完全打电话。
No. The main thread that is calling t1.join()
will stop running and wait for the t1
thread to finish. The t2
thread is running in parallel and is not affected by t1
or the t1.join()
call at all.
就try / catch而言, join()
throws InterruptedException
意味着调用 join()
的主线程本身可能会被另一个线程中断。
In terms of the try/catch, the join()
throws InterruptedException
meaning that the main thread that is calling join()
may itself be interrupted by another thread.
while (true) {
在中加入
循环是一种奇怪的模式。通常,您将执行第一次连接,然后在每种情况下适当地处理 InterruptedException
。无需将它们放在循环中。
Having the joins in a while
loop is a strange pattern. Typically you would do the first join and then the second join handling the InterruptedException
appropriately in each case. No need to put them in a loop.
这篇关于这个线程加入代码是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!