我需要一个解决方案来正确地停止Java中的线程.
我有IndexProcessor实现Runnable接口的类:
public class IndexProcessor implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
@Override
public void run() {
boolean run = true;
while (run) {
try {
LOGGER.debug("Sleeping...");
Thread.sleep((long) 15000);
LOGGER.debug("Processing");
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
run = false;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有ServletContextListener开始和停止线程的类:
public class SearchEngineContextListener implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);
private Thread thread = null;
@Override
public void contextInitialized(ServletContextEvent event) {
thread = new Thread(new …Run Code Online (Sandbox Code Playgroud) 如何在java中停止或中断睡眠线程?我有一个同步数据并在run()方法中休眠10分钟的线程,如果我想通过在线程休眠时停止线程来停止同步.怎么能实现这一目标?
在下面的示例中,我试图优雅地终止两个线程。消费者线程在睡眠时被中断,这应该将 isInterrupted 标志设置为 true。但是 !Thread.currentThread().isInterrupted() 检查 while 循环似乎仍然返回 = false 因为它不会终止消费者线程。
将下面的代码复制并粘贴到 IDE 中进行检查:
public class ThreadInterruptExample {
public static void main(String[] args) throws InterruptedException {
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(1);
ThreadInterruptExample ie = new ThreadInterruptExample();
Producer producer = ie.new Producer(queue);
Consumer consumer = ie.new Consumer(queue, producer);
producer.start();
consumer.start();
Thread.sleep(1000);
producer.cancel();
consumer.cancel();
}
class BaseQueue extends Thread {
protected final BlockingQueue<String> queue;
public BaseQueue(BlockingQueue<String> queue) {
this.queue = queue;
}
public void cancel() {
System.out.println(this.getName() + " - Shutting down"); …Run Code Online (Sandbox Code Playgroud)