美好的一天! 我得到了有关在java中同步线程的问题。我正在开发创建计时器的程序,并允许重置它,删除和停止。只是为了学习如何使用线程。在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();
我想你不理解什么“同步”意味着与线程编程有关。它跟时间没有任何关系。 – 2011-03-10 19:00:36
@布莱恩罗奇 是的,你是对的。我在这里学习很多东西。 – ExiRe 2011-03-10 19:17:31