線程的中斷.interrupt

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.