线程对象.interrupt()

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

线程的中断.interrupt

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();
    }
}

 

相关文章:

  • 2021-11-28
  • 2021-12-05
  • 2021-04-13
  • 2021-12-06
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
猜你喜欢
  • 2021-10-04
  • 2021-10-11
  • 2020-03-01
  • 2018-11-28
  • 2021-05-20
  • 2021-07-22
相关资源
相似解决方案