线程的停止
1.停止一个线程,我们一般都会通过一个变量去控制的。
package com.cn.thread;
/**
* Author:Liu Zhiyong
* Version:Version_1
* Date:2016年7月7日12:46:11
* Desc:线程的停止
* 1.停止一个线程,我们一般都会通过一个变量去控制的。
* 2.如果需要停止一个处于等待状态下的 线程,我们需要通过变量配合notify()方法或者interrupt()方法来使用。
*/
public class Demo11 extends Thread{
boolean flag = true;
public Demo11(String name) {
super(name);
}
@Override
public synchronized void run() {
int i = 0;
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
// e.printStackTrace();
System.out.println("接收到了异常");
}
System.out.println(Thread.currentThread().getName() + ":" + i);
i++;
}
}
public static void main(String[] args) {
Demo11 d = new Demo11("木先森");
d.setPriority(10);
d.start();
for(int i=0; i<100; i++){
System.out.println(Thread.currentThread().getName() + ":" + i);
//当主线程的i是50的时候停止狗娃线程
if(i == 50){
// d.stop();//过时了
// d.interrupt();//根本无法停止一个线程
d.flag = false;
d.interrupt();//把线程的等待状态强制清除,它还将收到一个 InterruptedException。
/*synchronized(d) {
d.notify();
}*/
}
}
}
}