java - 在java中使用线程计算所用的总时间

标签 java multithreading swing

我有这个使用线程来计算从按下开始按钮到未按下停止按钮所耗时的java代码。

我想仅使用线程来执行此操作

import javax.swing.*;
import java.awt.event.*;

// This will count the elapsed time between running time of two threads.
class ThreadGame {

    JButton button;
    MyAction my_action;

    public static void main(String[] args) {
        ThreadGame tg = new ThreadGame();
    }

    public ThreadGame() {
        JFrame frame = new JFrame("Calculate time - Game");
        button = new JButton("Start");
        button.addActionListener(new MyAction());
        frame.add(button);
        frame.setSize(400, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    class MyAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            String text = (String) e.getActionCommand();

            final Timer timer = new Timer();

            if (text.equals("Start")) {
                button.setText("Stop");

                Thread start_time = new Thread() {
                    public void run() {
                        timer.startTime();
                    }
                };

                start_time.start();
                try {
                    start_time.join();
                } catch (Exception e1) {
                }

            } else {
                Thread stop_time = new Thread() {
                    public void run() {
                        timer.stopTime();
                    }
                };

                Thread get_time = new Thread() {
                    public void run() {
                        timer.getElapsedTime();
                        System.out.println(timer.elapsed);
                    }
                };
                stop_time.start();
                try {
                    stop_time.join();
                } catch (Exception e2) {
                }

                get_time.start();

                button.setText("Start");
            }
        }
    }

    class Timer {
        public double startTime = 0.0;
        public double stopTime = 0.0;
        public boolean running = false;
        public double elapsed = 0.0;

        public void startTime() {
            this.startTime = System.nanoTime();
            this.running = true;
        }

        public void stopTime() {
            this.stopTime = System.nanoTime();
            this.running = false;
        }

        // Elasped time in seconds
        public double getElapsedTime() {
            // double elapsed;
            if (running) {
                elapsed = ((System.nanoTime() - startTime) / 1000);
            } else {
                elapsed = ((stopTime - startTime) / 1000);
            }
            return elapsed;
        }
    }
}

编辑:我已经理解了问题:timer范围是问题所在。

编辑 2: 好吧,看来我只能在一个线程中使用 suspendresume

最佳答案

问题是按下开始按钮启动的不同 Timer 对象与按下停止按钮按钮停止的Timer 对象不同,因为 Timer每次调用 actionPerformed(...) 方法时都会创建对象。

Timer 需要是 MyAction 类中的一个字段。您也不需要所有线程启动/连接,因为 Timer 对象非常简单且快速。

实际上,您可以使用 startTimeMillis 长字段来代替计时器。像这样的东西:

class MyAction implements ActionListener {
   private long startTimeMillis;
   public void actionPerformed(ActionEvent e) {
        String text = (String) e.getActionCommand();

        if (text.equals("Start")) {
            startTimeMillis = System.currentTimeMillis();
            ...
         } else {
            System.out.println(System.currentTimeMillis() - startTimeMillis);
         }
     }
 }

关于java - 在java中使用线程计算所用的总时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12392516/

相关文章:

java - 设置保存位置时,youtube-dl 将 "C:\"转换为 "C#\"

java - 运行ProcessBuilder后如何在指定位置生成输出文件 ("executable.exe", "InputFile").start()

c# - 类似于 C# 的 jMonkey 引擎

java - 支柱2 : Using data from other actions

java - 我如何在 Swing 中捕获此异常?

java - 创建后绘制组件

java - 解析并检索日期时间的时区偏移量

c++ - 如何区分 C++ 中的高性能和低性能内核/线程?

java - Android - 在主 UI 线程中绘制 Google map 的辅助线程

multithreading - 在请求之间共享应用程序线程池