java线程停止的有哪些方法
Java线程停止的方法有以下几种:
public class MyThread extends Thread {
private boolean flag = true;
@Override
public void run() {
while (flag) {
// 线程履行的任务
}
}
public void stopThread() {
flag = false;
}
}
可以通过调用stopThread()方法设置标志位为false,从而停止线程。
public class MyThread extends Thread {
@Override
public void run() {
while (!Thread.interrupted()) {
// 线程履行的任务
}
}
}
可以通过调用interrupt()方法中断线程。
public class MyThread extends Thread {
@Override
public void run() {
while (true) {
// 线程履行的任务
}
}
}
可以通过调用stop()方法停止线程,但不推荐使用。
public class MyThread extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
// 线程履行的任务
}
}
}
可以通过调用interrupt()方法中断线程,并通过isInterrupted()方法判断线程是否是被中断。
整体来讲,推荐使用标志位或interrupt()方法来停止线程,而不推荐使用stop()方法。
TOP