Cyh的博客

Email:kissyan4916@163.com
posts - 26, comments - 19, trackbacks - 0, articles - 220

线程2--停止线程

Posted on 2009-06-02 20:11 啥都写点 阅读(292) 评论(0)  编辑  收藏 所属分类: J2SE
关键技术:
  • JDK1.1以前使用Thread的stop方法停止线程,现在已经不推荐使用了,原因是它可能引起死锁。
  • 为线程设置一个布尔属性,标志线程是否运行,在run方法中适当地检测该标志位,只有当它的值为true时,才继续往下执行。但需要停止线程时,只需设置标志位为false即可。

package book.thread;
/**
 * 停止线程
 
*/
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();
    }
}



                                                                                                       --    学海无涯