美好的一天! 我得到了有關在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