public void run() {
assignPlayer();
for(int i = 0; i < numPlayers; i++) {
PlayerListener listener = new PlayerListener(fromPlayer.get(i), this, i);
new Thread(listener).start();
}
return;
}
我正在实现一个套接字游戏。每个游戏都有 2 名玩家,并且每个游戏都有自己的线程。上面的 run 方法将 PlayerListener(这是一个 Runnable 对象)分配给每个玩家以监听他们的传入输出流,并在有要执行的操作时调用游戏对象中的某些方法。一切都运行良好,但我在想我的游戏线程什么时候会死掉,所以我故意在PlayerListener赋值完成后设置“return”(但我认为赋值完成后,不会有任何语句,所以run方法会运行反正 )。无论如何,我的游戏仍在运行,我的线程不应该死掉,我的游戏对象也随之死掉吗?
这是因为 PlayerListener 对象仍然不时调用游戏对象的方法,所以该对象没有被垃圾收集?
我读了这篇文章When does a Java Thread reach the 'Die' State 。它指出“如果 run() 方法返回”,所以我很好奇......
最佳答案
so I intentionally set "return" after the PlayerListener assignment is finished
您的 return;
是无关的,因为它位于方法的末尾。如果没有它,该方法将返回。线程等待其 fork 的线程的唯一时间是您在每个线程上专门调用 thread.join()
的情况。
Anyway, my game is still running, shouldn't my thread dies and my game object dies along with it?
您 fork 的线程很可能是非守护线程。当 JVM 退出时,守护线程也会退出,但 JVM 会等待所有非守护线程自行退出。当您 fork 线程时,它们将呈现 fork 它们的线程的守护进程状态。如果您希望这些线程在 run()
方法完成后退出,请这样说:
Thread thread = new Thread(listener);
// make sure the threads will be killed when all other threads finish
thread.setDaemon(true);
thread.start();
I read the post When does a Java Thread reach the 'Die' State. It states that "If the run() method returns", so I was curious...
对。如果您处于线程的 run() 方法中,则当 run() 方法完成时,该线程将完成。然而,同样,循环中 fork 的线程将使应用程序保持运行,除非它们被专门设置为守护线程。
关于java - 为什么我的线程没有死?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22851716/