停止Java中的线程 [英] Stopping Thread in Java

查看:66
本文介绍了停止Java中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的Java代码:

if i have got such java code:

public static void main(String[] args)
{
    for(int i = 0;i<100;i++)
    {
        Future<?> f = ThreadPoolManager.getInstance().schedule(new START(), 500);
        f.cancel(true);
    }
}
private class START implements Runnable
{
    @Override
    public void run()
    {
        System.out.println(1);
    }
}

并在调试中运行它,我可以看到所有这些线程(在取消之后)仍在运行,所以它们也占用了我的内存吗?如果是的话,我怎么能完全销毁那些线程?

And run it in debug, i can see that all of those threads(after cancel) are still running, so are they taking my memory too? And if yes, how can i destroy those Threads completely?

推荐答案

cancel(true)在您的线程上调用interrupt(),仅此而已.因此,您需要在run()方法中正确处理它.对于您的简单情况,您的线程将完成其执行,并且它们的对象将由GC清除.

cancel(true) calls interrupt() on your thread, nothing more. So, you need to handle it properly in your run() method. For your simple case your threads will finish their execution and their objects will be cleared by GC.

这篇关于停止Java中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆