Thread synchronization in java

Good afternoon! I had a problem with thread synchronization in java. I am developing a program that creates timers and allows reset to delete and stop. Just learn how to use streams.

The problem is that the code only gives synchronization for some time ... I can not understand my error. Perhaps my path is wrong, so I would like to know how to solve this problem.

I have the following code:

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;
} 

I call this class the following:

StopWatch s = new StopWatch(1);
          s.startClock();
StopWatch s2 = new StopWatch(2);
          s2.startClock();
+3
source share
5 answers

I think you may have misunderstood "synchronized."

, - , . "" , startClock ....

, Java ( ) , , , , JVM- ..

, Thread.sleep(...) , , , . .

:

System.currentTimeMillis(), .

+7

, " ?" , , startClock, , ( , ). , , Time ( AtomicLong).

+2

, "synchronize". , , , - StartClock(), , . , , .

0
0

, , . , , , .

, CyclicBarrier CountDownLatch. "" ( ) , - .

However, keep in mind that it is not possible for multiple threads to do something in the same instant. You can only try to do this at about the same time. The rest is subject to OS planning on the kernels in the system. And if you have one core, they will never work at the same time.

0
source

All Articles