gpt4 book ai didi

java - 不是 "join"中断线程可以吗?

转载 作者:行者123 更新时间:2023-11-29 03:02:16 25 4
gpt4 key购买 nike

我有一个纸牌游戏应用程序,其中“机器人”手必须在多个弃牌中进行选择以优化其手牌。所以我正在考虑可能的弃牌选择,然后计算手牌估值。我使用两种不同的方法进行手工估价;一种是详尽的但可能非常昂贵,另一种是启发式的并且非常快。一旦计算时间超过 500 毫秒,我就从穷举法切换到启发式方法。我通过在可能的丢弃物上启动线程,然后还启动 sleep 线程来做到这一点。当它结束 sleep 时,它会中断其他线程,然后我用启发式方法重新运行它们。

所有这一切都工作正常。但在检查连接循环中的中断线程时,我立即抛出一个 InterruptedException 以便调用者知道重新运行计算。这样做时,我永远不会加入其他 中断的线程。这是资源泄漏,还是最终会清除其他线程?

代码 fragment 如下:开始我的主题:

    for (Card disCard : cardsWithAdded) {
CardList cards = new CardList(cardsWithAdded);
cards.remove(disCard);

testHand[iThread] = new ThreadedHand(this.hand.getRoundOf(), cards, disCard, this.method, isFinalTurn); //creates new hand with replaced cards
t[iThread] = new Thread(threadGroup,testHand[iThread]);
t[iThread].start(); //calls meldAndEvaluate
iThread++;
}

在 sleep 线程中打断它们:

        public void run() {
final long sleepStartTime = System.currentTimeMillis();
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// if interrupted, this means the other threads finished their work before the sleep ended
return;
}
threadGroup.interrupt(); //interrupt the other calculation threads
}

检查计算线程是否中断(在循环中):

        if (Thread.interrupted()) {
throw new InterruptedException();
}

在运行中设置标志:

        public void run()  {
threadStart = System.currentTimeMillis();
wasThreadInterrupted = false;
try {
this.meldAndEvaluate(this.method, EasyComputerPlayer.this , this.isFinalTurn);
} catch (InterruptedException e) {
//just break out of this thread
threadStop = System.currentTimeMillis();
wasThreadInterrupted = true;
}
threadStop = System.currentTimeMillis();
}

以及我在第一个中断的线程处中断的连接:

         for (int iThread=0; iThread < this.numThreads; iThread++) {
try {
t[iThread].join();
} catch (InterruptedException e) {
throw new InterruptedException(String.format("%s-%s: findBestHandFinish interrupted in join()...",FiveKings.APP_TAG,Thread.currentThread().getName()));
}
//can only test this flag after we've rejoined the thread to this one
if (testHand[iThread].wasThreadInterrupted()) throw new InterruptedException(String.format("After join: Thread %s shows was-interrupted - throwing exception", t[iThread].getName()));

最佳答案

加入线程既不是必需的……也不足以防止资源泄漏。

现实中:

  • 当线程终止时,线程堆栈符合回收条件1。如果线程没有适本地响应中断(即通过终止自身),那么你就有了资源泄漏。

  • Thread 对象在线程终止并且没有对该对象的可达引用后可以回收。但是Thread对象的泄漏是简单的内存泄漏,不是一般意义上的资源泄漏。


1 - 当 run() 方法正常终止(通过返回)或异常终止(作为未检查异常传播的结果)时,线程终止。

关于java - 不是 "join"中断线程可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113013/

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