你好!我遇到了一个关于Java中线程同步的问题。我正在开发一个程序,它创建定时器并允许重置、删除和停止。只是为了学习如何使用线程。
问题在于代码仅在一段时间内进行同步...我无法理解我的错误。也许我的方式有误,所以我想知道如何解决这个问题。
我有以下代码:
public class StopWatch
{
//Create and start our timer
public synchronized void startClock( final int id )
{
//Creating new thread.
thisThread = new Thread()
{
@Override
public void run()
{
try
{
while( true )
{
System.out.printf( "Thread [%d] = %d\n", id, timerTime );
timerTime += DELAY; //Count 100 ms
Thread.sleep( DELAY );
}
}
catch( InterruptedException ex )
{
ex.printStackTrace();
}
}
};
thisThread.start();
}
…
//Starting value of timer
private long timerTime = 0;
//Number of ms to add and sleep
private static final int DELAY = 100;
private Thread thisThread;
}
我会像这样调用这个类:
StopWatch s = new StopWatch(1);
s.startClock();
StopWatch s2 = new StopWatch(2);
s2.startClock();