停止线程
本来Thread类中有一个stop方法可以用来停止线程,但是却过时了,那么又该怎样停止线程呢?
线程运行其实运行的是run方法中的代码,那么只要将run方法停止,那么线程也就随之停止了。
一般线程的运行与循环相结合,那就好办了。将标记修改,那么run方法就会结束。
class StopThread implements Runnable {
private boolean flag = true;
public void run() {
while (flag) {
System.out.println(Thread.currentThread().getName() + "-----");
}
}
public void changeFlag() {
flag = false;
}
}
public class Stop {
public static void main(String[] args) {
int num = 0;
StopThread s = new StopThread();
Thread t1 = new Thread(s);
Thread t2 = new