gpt4 book ai didi

java - 如何在完成另一个线程后停止一个线程?

转载 作者:行者123 更新时间:2023-11-30 11:22:12 24 4
gpt4 key购买 nike

class test
{
public static void main(String[] args) {


Thread th=new Thread()
{

public void run(){

for (int i = 1; i <= 18; i++) {
System.out.println("run:"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
}

}};
Thread y=new Thread()
{
public void run() {
for (int i = 1; i < 10; i++) {
System.out.println("stop:"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
}

}

};

th.start();
y.start();
for (int i = 0; i < 5; i++) {
System.out.println("main:"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block

}

}
System.out.println("main completed");
}

}

这里我想在线程 y 完成执行后立即停止线程 th,我该怎么做?

最佳答案

您可以使用volatile boolean 变量并将其设置为false。线程 y 完成后使其true。在条件检查时停止所需的线程。

关于java - 如何在完成另一个线程后停止一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21829071/

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