roo*_*orr 4 java multithreading
我面临着一种情况,我需要停止执行程序服务线程的运行。
我已经阅读过其他帖子中的解决方案,其中提到使用 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 {
// TODO Auto-generated method stub
ExecutorService service = Executors.newCachedThreadPool();
TestRunnable test = new TestRunnable();
service.execute(test);
Thread.sleep(1000);
System.out.println("About to Interrupt");
test.getT().interrupt();
}
}
Run Code Online (Sandbox Code Playgroud)
执行此操作的唯一正确方法是与您的任务相对cancel应Future,并且在您的任务中,您应该定期检查线程是否已被中断。
像这样的东西:
public class Task implements Callable<Void> {
@Override
public Void call() throws InterruptedException {
while(true) {
// Check regularly in your code if the thread has been
// interrupted and if so throws an exception to stop
// the task immediately
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Thread interrupted");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
那么你的主要代码将是:
ExecutorService service = Executors.newCachedThreadPool();
// My task
Task task = new Task();
// Submit the task and get the corresponding future
Future<?> future = service.submit(task);
...
// Cancel the task which will interrupt the thread that was executing the
// task if any
future.cancel(true);
Run Code Online (Sandbox Code Playgroud)