I faced the following code in our project:
synchronized (Thread.currentThread()){ //some code }
I don't understand the reason to use synchronized on currentThread
.
Is there any difference between
synchronized (Thread.currentThread()){ //some code }
and just
//some code
Can you provide an example which shows the difference?
more in details this code as follows:
synchronized (Thread.currentThread()) { Thread.currentThread().wait(timeInterval); }
It looks like just Thread.sleep(timeInterval)
. Is it truth?
The currentThread() method of thread class is used to return a reference to the currently executing thread object.
Thread synchronization basically refers to The concept of one thread execute at a time and the rest of the threads are in waiting state. This process is known as thread synchronization. It prevents the thread interference and inconsistency problem. Synchronization is build using locks or monitor.
A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method. This block is referred to as a synchronized block.
Synchronization is a process of handling resource accessibility by multiple thread requests. The main purpose of synchronization is to avoid thread interference. At times when more than one thread try to access a shared resource, we need to ensure that resource will be used by only one thread at a time.
consider this
Thread t = new Thread() { public void run() { // A synchronized (Thread.currentThread()) { System.out.println("A"); try { Thread.sleep(5000); } catch (InterruptedException e) { } } } }; t.start(); synchronized (t) { // B System.out.println("B"); Thread.sleep(5000); }
blocks A and B cannot run simultaneously, so in the given test either "A" or "B" output will be delayed by 5 secs, which one will come first is undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With