java如何用一个方法停止另外一个方法的运行
Java中没有直接停止另外一个方法运行的方法,但可以通过以下方法实现:
- 使用共享变量或标志位
在一个线程中定义一个共享变量或标志位,另外一个线程中通过不断地检查这个变量或标志位的值来决定是否停止运行。例如:
public class Example {
private volatile boolean stop = false;
public void run() {
while (!stop) {
// do something
}
}
public void stop() {
stop = true;
}
}
其中run()方法会不断地执行某些操作,而stop()方法会将stop变量设置为true,从而停止run()方法的运行。
- 使用Thread.interrupt()
在一个线程中调用另外一个线程的interrupt()方法,从而中断另外一个线程的运行。例如:
public class Example implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// do something
}
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Example());
thread.start();
// do something
thread.interrupt();
}
}
其中Example类实现了Runnable接口,并在run()方法中不断地执行某些操作,而Main类中创建了一个线程并启动它,然后在某个时刻调用了线程的interrupt()方法,从而停止线程的运行。
需要注意的是,在使用interrupt()方法时需要在run()方法中检查当前线程是否被中断,如果被中断则停止运行。
原文地址: https://www.cveoy.top/t/topic/snp 著作权归作者所有。请勿转载和采集!