【发布时间】:2015-02-12 16:56:29
【问题描述】:
我在停止线程时遇到了一些问题。
我试过单独和一起打电话给Thread.join() 和Thread.interrupt(),但我无法正常工作。
我在每个类中都有一个while 循环,只要一个名为running 的布尔值等于true,它就会运行。
然后我通过调用一个名为stop 的方法来停止程序。 stop 方法仅将 running 设置为 false,以便退出 while 循环。
编辑代码:
public class Game implements Runnable {
// The Thread
private Thread thread;
// The program's running state
private boolean running = false;
// Create the Thread and the rest of the application
public void create() {
// Create the Thread
thread = new Thread(this, "Game");
// Start the Thread
thread.start();
// Set the program's running state to true
running = true;
}
public void run() {
while(running) {
// Render, update etc...
}
// When the while loop has exited
// (when running is false (when the stop method has been called))
try {
// Join the thread
thread.join();
// Interrupt the thread
thread.interrupt();
} catch(InterruptedException e) {
// Print the exception message
e.printStackTrace();
}
// Exit the program
System.exit(0);
}
// Stop the game
public void stop() {
// Set the program's running state to false
running = false;
}
// The main method
public static void main(String[] args) {
// Create a new instance of Game and start it
new Game().create();
}
【问题讨论】:
-
没有足够的代码。请注意,检查线程是否被中断的标准方法是检查
Thread.currentThread().isInterrupted()。仔细阅读 javadoc。或者更好的是,不要直接使用线程并使用ExecutorService。并购买 JCIP。 -
对不起,我没有提到我在创造一个游戏,所以不使用线程不是一个选项。另外,你需要多少代码?
-
你真的认为 join() 和 interrupt() 会将你的
running变量设置为 false 吗?这就是那些方法的 javadoc 所说的吗? -
这是它的基础。我把所有的渲染等都放在了循环里面。
-
@user1676075
AtomicBoolean在volatile之外没有任何东西,如果你只需要set和get。
标签: java multithreading loops