用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

java 停止线程

2012-11-23 作者: 程序猿style举报

[java]代码库

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


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...