zoukankan      html  css  js  c++  java
  • 线程的中断.interrupt

    线程对象.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();//如果thread=new Thread(new Runnalbe{...}),this无效
                            this.interrupt();//this指代Thread()
                        }
                        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();
        }
    }
  • 相关阅读:
    HttpClient
    spring入门
    morphia进阶
    morphia基本API方法
    mangodb数据库框架morphia注解
    学与思
    解决vscode执行yarn启动项目报错
    使用swiper+动画实现轮播图自动播放
    vue中使用el-tree实现一行显示多条数据
    使用git命令提交部分修改代码
  • 原文地址:https://www.cnblogs.com/xixixing/p/9571045.html
Copyright © 2011-2022 走看看