線程的暫停與恢復


使用頂級父類Object的wait()暫停, notify()喚醒方法。這兩個方法,必須獲得obj鎖,也就是必須寫在synchronized(obj) 代碼段內。

public class Demo extends JFrame {
    JLabel label;
    JButton btn;
    String[] nums = {"1", "2", "3", "4", "5"};

    public Demo() {
        setTitle("中獎座位號");
        setBounds(200, 200, 300, 150);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        label = new JLabel("0");//初始值0
        label.setFont(new Font("宋體", Font.PLAIN, 42));
        label.setHorizontalAlignment(SwingConstants.CENTER);//文本居中
        getContentPane().add(label, BorderLayout.CENTER);
//label內容隨機變化
        MyThread t = new MyThread();//創建自定義線程對象
        t.start();//啟動線程

        btn = new JButton("暫停");
        getContentPane().add(btn, BorderLayout.SOUTH);
        //按鈕的動作監聽事件
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String btnName = btn.getText();
                if (btnName.equals("暫停")) {
                    btn.setText("繼續");
                    t.toSuspend();//如果暫停,則線程wait
                } else {
                    btn.setText("暫停");
                    t.toResume();
                }
            }
        });
        setVisible(true);
    }

    class MyThread extends Thread {//創建自定義線程
        //控制while循環語句的true/false,是否執行wait()
        private boolean suspend = false;//默認不執行wait

        public synchronized void toSuspend() {//同步方法
            suspend = true;
        }//執行wait

        public synchronized void toResume() {//不執行wait,並喚醒暫停的線程
            suspend = false;
            notify();//當前等待的進程,繼續執行(喚醒線程)
        }

        public void run() {//線程執行的內容
            while (true) {
                int randomIndex = new Random().nextInt(nums.length);//隨機索引位置
                String num = nums[randomIndex];
                label.setText(num);//更改label內容
                synchronized (this) {//同步代碼塊,加鎖
                    while (suspend) {
                        try {
                            wait();//線程進入等待狀態
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM