gpt4 book ai didi

java - 停止可运行对象相当于停止线程吗?

转载 作者:行者123 更新时间:2023-12-01 17:57:18 27 4
gpt4 key购买 nike

鉴于此代码:

public class Game implements Runnable {
private volatile boolean stop;

public Game() {
...
}

public void run() {
while(!stop) {
// play game
}
}

public void stopGame() {
stop = true;
}
}

public class Main {

public static void main(String[] args){
Game g = new Game(); // Game class implements Runnable
Thread t = new Thread(g);
t.start();
// do the two method calls below effectively do the same thing?
t.interrupt();
g.stopGame();
}

}

stopGame() 终止线程是否与使用中断或 java.lang.Thread 方法终止线程一样有效? (我不太熟悉如何使用 Thread 方法终止线程。)

此外,如果 stopGame() 是终止线程的最佳方法,那么如果他们只能访问 Thread 实例,是否可以调用它,如下所示:

public static void Main(String[] args){
List<Thread> threads = new ArrayList<Thread>();
threads.add(new Thread(new Game()));
// can you access the Game instance given the Thread instance
// or do you need to hold onto the reference of the Game instance?
threads.get(0).stopGame(); // for example, this won't work.
}

最佳答案

Does stopGame() stop the thread as effectively as using something like interrupt, or a java.lang.Thread method to kill the thread? (I'm not too familiar with how you would kill a thread using a Thread method.)

停止线程的最佳方法是从 run() 方法返回。

您的 stopGame() 调用会在下一次循环中导致这种情况。但如果该循环包含阻塞调用,则下一次传递可能会在延迟后发生,或者永远不会发生。

终止线程的方法已被弃用,因为它们本质上是不安全的。

Thread.interrupt() 不保证停止任意线程。它会唤醒一些阻塞调用。 Runnable 在捕获 InterruptedException 时停止是很常见的,但并不普遍。来自 Java tutorial on interrupts :

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

一种方法是两者设置用户定义的标志并调用Thread.interrupt()。这将中断任何阻塞调用,并且即使 Runnable 调用的代码已捕获 InterruptedException 或清除了中断状态标志,它也会工作。

Also, in the case that stopGame() is the best way to kill a thread, is there any to call it if they only had access to the Thread instance like below:

您可以子类化 Thread 来保存游戏,并在子类中提供一个方法来停止游戏。但是,单独跟踪 Runnable 实例通常会更容易。

关于java - 停止可运行对象相当于停止线程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43667388/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com