我在用Java做一个简单的程序。
2个线程应将其id
附加到字符串中,然后第三个线程将整个字符串散列。这应该发生5次。它确实起作用,问题在于该程序仅保持运行并且不会停止执行。我尝试了break
,但仍然挂起。
我假设正在发生某种僵局,但我不知道为什么或如何。
public void run()
{
while(numOfIterations > 0)
{
if (numOfIterations == 0){
break;
}
if(this.id == "A")
{
appendThread(this.id);
}
else if(this.id == "B")
{
appendThread(this.id);
}
else
{
hashThread();
}
try
{
Thread.sleep(interval);
if(this.nextThread.isAlive())
{
nextThread.interrupt();
}
else
{
nextThread.start();
}
Thread.sleep(Long.MAX_VALUE);
}
catch (InterruptedException e)
{
System.out.println("Interrupted Thread : "+ this.iD);
}
}
}
注意:
run
方法位于扩展Thread的类的内部,该类具有称为nextThread
的属性(基本上是对应该执行下一个任务的线程的引用)。线程1->线程2->线程3->线程1 ...)。
appendThread()
方法将id附加到字符串,而hashThread
将字符串哈希。两种方法都将
numOfIterations
变量减少一个。这是输出:
hashed word = b86fc6b051f63d73de262d4c34e3a0a9
numOfIterations : 4
Interrupted Thread : A
Interrupted Thread : B
Interrupted Thread : C
hashed word = a63e3d9e4d46287e71ec1248d1be5782
numOfIterations : 3
Interrupted Thread : A
Interrupted Thread : B
Interrupted Thread : C
hashed word = 444b8618908e49ca64c8eafab94add38
numOfIterations : 2
Interrupted Thread : A
Interrupted Thread : B
Interrupted Thread : C
hashed word = 535cfc91d9e96b57395000fdae460bf1
numOfIterations : 1
Interrupted Thread : A
Interrupted Thread : B
Interrupted Thread : C
hashed word = 3e9c9cfb98a356ff155fa67abbbaccb9
numOfIterations : 0
Interrupted Thread : A
输出正确,唯一的问题是程序没有结束。另外,请注意输出如何以
Interrupted Thread : A
结尾,而不是B或C。任何帮助将不胜感激。
最佳答案
许多小时后,我才知道发生了什么事。
由于每个线程都在等待被上一个线程中断,因此在线程B和C等待线程A唤醒它们时发生了死锁,但是A已经退出了该函数。Interrupted Thread : A
在最后打印的原因是线程A终止了它的方法,但线程B和C仍在 hibernate 。
因此,我只需要通过调用nextThread.interrupt()使线程A中断线程B,然后使其存在该函数即可。这样,A在退出方法之前唤醒了B,B唤醒了C,因此所有线程都可以退出该函数。
将此添加到函数的末尾解决了我的问题。
if (numOfIterations == 0){
nextThread.interrupt();
}
关于java - 使线程终止并编程结束执行时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61839183/