我面临着一种情况,我需要停止执行程序服务线程的运行。
我已经阅读过其他帖子中的解决方案,其中提到使用 Future 对象并取消任务。
但我宁愿尝试不同的方法。
如果这种方法有任何问题,请任何人告诉我。
以下是我的 Runnable 课程。
public class TestRunnable implements Runnable {
Thread t;
@Override
public void run() {
// TODO Auto-generated method stub
setT(Thread.currentThread());
while(true)
{
if(Thread.currentThread().isInterrupted())
{
System.out.println("From Inside thread, Exiting");
System.exit(0);
}
}
}
public void setT(Thread t) {
this.t = t;
}
public Thread getT() {
return t;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我的主要方法:
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ruunTest {
public static void main(String[] args) throws IOException, InterruptedException {
// …Run Code Online (Sandbox Code Playgroud)