package cn.breeziness123.zhx;
/**
* 终止线程的方法:标志位的方法
* 终止线程我们一般不使用JDK提供的stop()/destroy()方法(它们本身也被JDK废弃了)。
* 通常的做法是提供一个boolean型的终止变量,当这个变量置为false,则终止线程的运行。
*/
public class ThreadDemo05 implements Runnable {
private boolean live = true;
private String threadName;
public ThreadDemo05(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
while (live) {
for (int i = 0;i<10;i++){
System.out.println(threadName+"--->"+i);
}
}
}
//提供终止线程的方法
public void termination(){
live = false;
}
public static void main(String[] args){
ThreadDemo05 th1 = new ThreadDemo05("线程A");
new Thread(th1).start();
for (int i = 0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"--->"+i);//打印主线程
}
th1.termination();//终止线程
}
}
终止线程的方法
猜你喜欢
转载自blog.csdn.net/qq_40731414/article/details/86644624
今日推荐
周排行