线程模拟打印(支持暂停功能)

public class MainFrame extends JFrame {

    private JButton printButton = new JButton("打印");
    private JButton suspendButton = new JButton("暂停");

    private JLabel printText = new JLabel("模拟小票打印");
    private JTextArea printTextArea = new JTextArea();

    //判断暂停、继续
    private boolean suspend = false;

    //新建一个对象
    Object lock = new Object();

    public MainFrame() {
        initFrame();
        bindEvent();
    }

    private void initFrame() {
        setTitle("模拟小票打印");
        setSize(800, 500);
        setVisible(true);
        setLayout(null);
        setResizable(false);
        setLocationRelativeTo(null);
        Font labelFont = new Font(Font.SERIF, Font.BOLD, 23);

        printText.setBounds(360, 30, 200, 50);
        printText.setFont(labelFont);

        printTextArea.setBounds(200, 100, 420, 160);
        printTextArea.setFont(labelFont);

        printButton.setBounds(new Rectangle(260, 300, 100, 50));
        printButton.setFont(labelFont);

        suspendButton.setBounds(new Rectangle(460, 300, 100, 50));
        suspendButton.setFont(labelFont);

        add(printButton);
        add(suspendButton);
        add(printText);
        add(printTextArea);
    }

    private void bindEvent() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        printTextArea.setText("准备打印");
        printButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                new Thread(() -> {
                    try {
                        synchronized (lock) {
                            for (int i = 10001; i < 100000; i++) {
                                printTextArea.setText("当前打印单号为:" + i);
                                Thread.sleep(1000);
                                //根据 suspend 来判断 是否让当前线程wait
                                while (suspend) {
                                    int n = i + 1;
                                    printTextArea.setText("打印暂停, 再次打印从" + n + "开始");
                                    lock.wait();
                                }
                            }
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }).start();
            }
        });

        //暂停/继续 操作
        suspendButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (suspend) {
                    suspend = false;
                    suspendButton.setText("暂停");
                    synchronized (lock) {
                        //唤醒当前线程
                        lock.notifyAll();
                    }
                } else {
                    suspend = true;
                    suspendButton.setText("继续");
                }
            }
        });
    }
}

👇exe 👇请看👇

 

 

posted @ 2018-11-14 20:49  令狐る侠  阅读(517)  评论(0编辑  收藏  举报