1. 程式人生 > >線程的暫停與恢復

線程的暫停與恢復

exit args gettext tac 循環 seo itl nds eth

技術分享圖片技術分享圖片技術分享圖片

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轉換 private boolean suspend = false; public synchronized void toSuspend() {//同步方法 suspend = true; } public synchronized void toResume() { 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(); } }

線程的暫停與恢復