gpt4 book ai didi

java - 销毁/停止线程

转载 作者:行者123 更新时间:2023-12-01 09:26:31 29 4
gpt4 key购买 nike

我有关于 Thread2 问题,我只是想澄清一些事情。使用以下代码:

public class MyThread implements Runnable {

Boolean StopThread = false;
Boolean DontLoop = false;
public MyThread(){}

public void Stop(Boolean stopThread){
this.StopThread = stopThread;
}

public void ThreadDontLoop(Boolean dontLoop){
this.DontLoop = dontLoop;
}

public void run(){
if(dontLoop){
while(true){
if(StopThread){
break; //Terminate WhileLoop, This will Stop and destroy the Thread also
}
}
}else{
//Does this mean the Thread will be destroy/terminate after this condition?
}
}
}

为了开始:

MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();

为了启动线程但不循环

ThreadDontLoop(false);
thread.start();

为了停止线程

myThread.Stop(true);

现在,根据这个LINK ,这就是线程被停止的方式。

所以我的第一个问题是,在上面的给定代码中,如果我调用 ThreadDontLoop(false); 然后 thread.start();,这是否意味着线程将启动,但在条件满足后,线程将停止并销毁?

第二个问题是,假设我调用 thread.start(); 然后我调用 myThread.Stop(true); 来停止 WhileLoop 并销毁线程。我没有遵循链接如何停止线程,因为我会有不同的条件,但我相信我想如何停止线程的逻辑是正确的?

最佳答案

您需要一个 volatile boolean 值,或者该值可以内联并且永远不会改变。

in the Given code above, what if I call ThreadDontLoop(false); then thread.start();, does this mean the Thread will Start but after the condition, the Thread will be stopped and destroy?

是的。

Let's say I call thread.start(); then later I call myThread.Stop(true); to stop the WhileLoop and Destroy the Thread. I didn't follow on how the link is stopped the thread since I will have a different condition, but I believe that the logic on how I would like to stop the Thread is correct?

如果您没有可见性问题(线程是否看到您的更改),它将停止。在问题中的代码中,很可能代码将被优化以假设线程永远不会看到更改。

关于java - 销毁/停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39791633/

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