Java中停止线程的方法有两种:一种是使用Thread.interrupt()方法,另一种是使用volatile boolean变量。
Java中停止线程的方法有两种:一种是使用Thread.interrupt()方法,另一种是使用volatile boolean变量。
1. 使用Thread.interrupt()方法:
Thread.interrupt()方将线程的中断标志设置为true,从而使线程停止执行。
代码示例:
public class MyThread extends Thread {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("MyThread is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
// 停止线程
MyThread.interrupt();
2. 使用volatile boolean变量:
使用volatile boolean变量来控制线程的运行状态,当变量值为false时,线程停止执行;当变量值为true时,线程继续执行。
代码示例:
public class MyThread extends Thread {
private volatile boolean running = true;
@Override
public void run() {
while (running) {
System.out.println("MyThread is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 停止线程
public void stopThread() {
running = false;
}
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(71条)