线程的暂停与恢复

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

猜你喜欢

转载自www.cnblogs.com/xixixing/p/9581902.html