关于一个多线程的码表问题

xiaoxiao2023-03-19  49

import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;class MyThread extends Thread { private JLabel label; private long time; private long endtime; public MyThread(JLabel label, long time) { this.label = label; this.time = time; } public void init() { endtime = System.currentTimeMillis() + time; } @Override public void run() { init(); while (true) { long runtime = endtime - System.currentTimeMillis(); time = runtime; if(runtime > 0){ label.setText(formatTime(runtime)); }else{ label.setText("GAME OVER"); } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } private String formatTime(long runtime) { int m = (int) (runtime / 1000 / 60); int s = (int) (runtime / 1000 % 60); int ss = (int) (runtime % 1000); return check(m) + ":" + check(s) + "." + check(ss); } private String check(int number) { return number > 9 ? "" + number : "0" + number; }}class ClockFrame extends JFrame { private JLabel label; private JButton button; private MyThread mt; private boolean bFlag = true;// 控制按钮的显示及线程的挂起恢复 public ClockFrame() { label = new JLabel(); label.setHorizontalAlignment(JLabel.CENTER); add(label, BorderLayout.CENTER); button = new JButton("暂停"); add(button, BorderLayout.NORTH); setBounds(222, 222, 222, 222); setVisible(true); mt = new MyThread(label, 10000L); mt.start(); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (bFlag) { button.setText("继续"); mt.suspend(); } else { button.setText("暂停"); mt.init(); mt.resume(); } bFlag = !bFlag; } }); }}public class ClockTest { public static void main(String[] args) { new ClockFrame(); }} 以上是一个多线程的码表程序,运行起来没有问题,但是用到了两个过时的方法,suspend,suspend,想请问如果用wait, notify这两个方法,应该怎么改这个程序,谢谢
转载请注明原文地址: https://www.6miu.com/read-4986720.html

最新回复(0)