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();
        }
    }
  • 相关阅读:
    10-2[RF] OOB validation
    5.css背景以及书写位置
    4.css基础
    3.表单form
    2.表格
    1.html基础
    正则表达式
    协程
    7.树与树算法
    6.排序与二分查找
  • 原文地址:https://www.cnblogs.com/xixixing/p/9571045.html
Copyright © 2011-2022 走看看