在java中同步线程

Exi*_*iRe 3 java multithreading

美好的一天!我遇到了在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;
} 
Run Code Online (Sandbox Code Playgroud)

我将此类称为:

StopWatch s = new StopWatch(1);
          s.startClock();
StopWatch s2 = new StopWatch(2);
          s2.startClock();
Run Code Online (Sandbox Code Playgroud)

mik*_*era 6

我想你可能误解了"同步".

这并不意味着线程在完全同步的时间内运行 - 而是一次只允许一个线程执行同步代码块.在你的情况下,"synchronized"没有区别,因为你从同一个线程调用startClock方法....

通常,在Java(实际上是大多数高级语言)中,即使您有多个内核,也不可能保证两个线程在完全相同的时钟时间执行操作,因为它们总是容易被OS调度程序或JVM延迟垃圾收集暂停等

此外,Thread.sleep(...)作为计时机制是不可靠的,因为它睡眠的数量只是近似值.你受线程调度程序的支配.

建议的解决方案:

如果你想要一个与线程无关的计时机制,请使用System.currentTimeMillis().