0

我想知道如何编写线程安全的秒表。下面是一个简单的秒表实现,它提供了秒表的基本操作,但它不是线程安全的。

现在,我能想到的就是为每个方法(start()、lap()、stop()、reset())添加同步。是否有其他方法可以在秒表上实现线程安全?

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Stopwatch {
    private long startTime;
    private long endTime;
    private boolean isRunning;

    // lapTimes is able to record all the lap time.
    private CopyOnWriteArrayList<Long> lapTimes;

    Stopwatch() {
        isRunning = false;
        lapTimes = new CopyOnWriteArrayList<Long>();
    }

    public void start() {
        if (!isRunning) {
            isRunning = true;
            startTime = System.currentTimeMillis();
        } else {
            throw new IllegalStateException("cannot start when running!");
        }
    }

    public void lap() {
        if (isRunning) {
            endTime = System.currentTimeMillis();
            lapTimes.add(endTime - startTime);
            startTime = endTime;
        } else {
            throw new IllegalStateException("cannot lap when not running!!");
        }
    }

    public void stop() {
        if (isRunning) {
            endTime = System.currentTimeMillis();
            lapTimes.add(endTime - startTime);
            isRunning = false;
        } else {
            throw new IllegalStateException("cannot stop when not running!");
        }
    }

    public void reset() {
        isRunning = false;
        lapTimes.clear();
    }

    public List<Long> getLapTime() {
        return lapTimes;
    }

}

我想要做的是由多个线程共享一个秒表对象。

假设我们有两个线程:线程 A 和线程 B。线程 A 启动秒表,并且晚了几秒钟,它调用了停止。当它刚刚结束 if 语句(stop 方法的第一行)时,线程 B 被调用,它也调用了 stop 方法。后来线程A继续执行stop方法,没有任何异常。

这不是我想要的,因为线程安全的秒表无法停止两次,我只想知道如何摆脱它。

4

1 回答 1

-1

您是否希望它是线程安全的,因为... (a) 多个线程可能正在启动秒表并进行圈数,或者 (b) 一个线程可能会启动秒表,而另一个线程可以使用同一个秒表完成一圈?

于 2012-06-25T00:55:38.607 回答