码迷,mamicode.com
首页 > 编程语言 > 详细

线程的中断.interrupt

时间:2018-09-01 18:04:32      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:info   string   demo   bar   str   分享图片   休眠   tac   you   

线程对象.interrupt()

注意,异常分析中要有break,否则无法中断

技术分享图片

public class Demo extends JFrame {
    private Thread thread;//定义线程
    final JProgressBar progressBar = new JProgressBar();//进度条

    public Demo() {
        setBounds(100, 100, 200, 100);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().add(progressBar, BorderLayout.NORTH);
        progressBar.setStringPainted(true);//显示数字
//使用匿名内部类实现线程对象
        thread = new Thread() {
            int count = 0;//进度数据

            public void run() {
                while (true) {//无限循环,一般在不知道循环次数时使用
                    progressBar.setValue(++count);
                    if (count == 20) {
                        //thread.interrupt();
                        this.interrupt();
                    }
                    try {
                        Thread.sleep(100);//休眠0.1s
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.out.println("20%处被中断");//抛出异常
                        break;//一定要有break,否则无法中断
                    }
                }
            }
        };
        thread.start();

        setVisible(true);
    }

    public static void main(String[] args) {
        new Demo();
    }
}

 

线程的中断.interrupt

标签:info   string   demo   bar   str   分享图片   休眠   tac   you   

原文地址:https://www.cnblogs.com/xixixing/p/9571045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!