栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何正确停止Java中的线程?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何正确停止Java中的线程?

IndexProcessor
类中,你需要一种设置标志的方法,该标志通知线程它将需要终止,类似于
run
你刚刚在类范围中使用的变量。

当你希望停止线程时,可以设置该标志并

join()
在线程上调用并等待其完成。

通过使用volatile变量或使用与用作变量的变量同步的getter和setter方法,确保该标志是线程安全的。

public class IndexProcessor implements Runnable {    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);    private volatile boolean running = true;    public void terminate() {        running = false;    }    @Override    public void run() {        while (running) { try {     LOGGER.debug("Sleeping...");     Thread.sleep((long) 15000);     LOGGER.debug("Processing"); } catch (InterruptedException e) {     LOGGER.error("Exception", e);     running = false; }        }    }}

然后在

SearchEngineContextListener

public class SearchEngineContextListener implements ServletContextListener {    private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);    private Thread thread = null;    private IndexProcessor runnable = null;    @Override    public void contextInitialized(ServletContextEvent event) {        runnable = new IndexProcessor();        thread = new Thread(runnable);        LOGGER.debug("Starting thread: " + thread);        thread.start();        LOGGER.debug("Background process successfully started.");    }    @Override    public void contextDestroyed(ServletContextEvent event) {        LOGGER.debug("Stopping thread: " + thread);        if (thread != null) { runnable.terminate(); thread.join(); LOGGER.debug("Thread successfully stopped.");        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/372364.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号