/**
 * 停止线程
 */
public class StopThread {
/** 线程对象 */
private ThreadA thread = new ThreadA();
/** 自定义线程类 */
class ThreadA extends Thread{
//用一个boolean值标记线程是否需要运行。
private boolean running = false;
//覆盖了父类的start方法,
public void start(){
//将running置为ture,表示线程需要运行
this.running = true;
super.start();
}
public void run(){
System.out.println("ThreadA begin!");
int i=0; 
try {
//如果running为真,说明线程还可以继续运行
while (running){
System.out.println("ThreadA: " + i++);
//sleep方法将当前线程休眠。
Thread.sleep(200);
}
} catch (InterruptedException e) {
} System.out.println("ThreadA end!");
}
public void setRunning(boolean running){
this.running = running;
}
}
/**
 * 启动ThreadA线程
 */
public void startThreadA(){
System.out.println("To start ThreadA!");
thread.start();
}
/**
 * 停止ThreadA线程
 */
public void stopThreadA(){
System.out.println("To stop ThreadA!");
thread.setRunning(false);
}

public static void main(String[] args) {
StopThread test = new StopThread();
//启动ThreadA线程
test.startThreadA();
//当前线程休眠一秒钟
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//停止ThreadA线程
test.stopThreadA();
}
}while(runing)不是个死循环了吗??

解决方案 »

  1.   

    while(runing)只要你不调用线程的stop方法,它就会一直运行。
    你的程序中test.stopThreadA(); 使线程停止运行了。
      

  2.   

    public void stopThreadA(){
      System.out.println("To stop ThreadA!");
        thread.setRunning(false);
    } 这里将running置为false了,线程的循环就结束了,线程也就退出了
      

  3.   

    这程序能运行吗?
    感觉不行  strat();
    和  run(); 方法都有 能用thread.strat(); 吗?
      

  4.   

    我先不管该程序能不能运行,你的程序有两个线程,一个主线程,一个是threadA线程。而cpu是以时间片的形式分别运行这俩个线程的。如果cpu只让threadA线程占用的话你的while(running)就是一个死循环,可是当主线程获得cpu时它就会执行test.stopThreadA(); 这条语句,将你的running的值改为FALSE,所以就没有表现出死循环的效果