通过设置标志位让线程停止
class MyThread
implements Runnable {
private boolean flag = true;
@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
while ( this.flag) {
System.out.println(Thread.currentThread().getName() + "线程运行,i = "
+ (i++));
}
}
public void stop() {
this.flag = false;
}
}
public class ThreadDemo {
/**
* 通过标志位让线程停止
*/
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread , "线程");
thread.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
//加个延时操作方便观察
e.printStackTrace();
}
//修改标志位,使运行的线程停止
myThread.stop();
}
}
private boolean flag = true;
@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
while ( this.flag) {
System.out.println(Thread.currentThread().getName() + "线程运行,i = "
+ (i++));
}
}
public void stop() {
this.flag = false;
}
}
public class ThreadDemo {
/**
* 通过标志位让线程停止
*/
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread , "线程");
thread.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
//加个延时操作方便观察
e.printStackTrace();
}
//修改标志位,使运行的线程停止
myThread.stop();
}
}
转载于:https://blog.51cto.com/haiyuanxi/927218