让线程终止并编程结束执行的问题

问题描述 投票:2回答:2

我正在用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结尾。

任何帮助将不胜感激。

java multithreading java-threads
2个回答
1
投票

[几个小时后,我弄清楚了发生了什么。由于每个线程都在等待被上一个线程中断,因此在线程B和C等待线程A唤醒它们而A已退出该函数时发生了死锁。

Interrupted Thread : A在最后打印的原因是线程A确实终止了它的方法,但线程B和C仍在休眠。

因此,我只需要通过调用nextThread.interrupt()使线程A中断线程B,然后该线程B就存在该函数。这样,A会在退出方法之前唤醒B,B会唤醒C,因此所有线程都可以退出该函数。

将其添加到函数的末尾解决了我的问题。

if (numOfIterations == 0){   
    nextThread.interrupt();
}

0
投票

您必须将其作为try中的if语句之一:

if(this.nextThread.isAlive()) { 
  nextThread.interrupt(); 
}
else if (numOfIterations == 0){ 
  break; 
} else { 
nextThread.start(); 
}
© www.soinside.com 2019 - 2024. All rights reserved.