• 线程的暂停与恢复


    使用顶级父类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();
        }
    }
  • 相关阅读:
    LG2664 树上游戏
    「NOI2007」 货币兑换
    「NOI2012」骑行川藏
    LG4721 【模板】分治 FFT
    LG4783 【模板】矩阵求逆
    test20181019 B君的第二题
    LOJ129 Lyndon 分解
    「NOI2017」泳池
    LG4723 【模板】常系数线性递推
    「AHOI / HNOI2017」礼物
  • 原文地址:https://www.cnblogs.com/xixixing/p/9581902.html
Copyright © 2020-2023  润新知