Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of using synchronized (Thread.currentThread()){...} in Java?

Tags:

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?

UPDATE

more in details this code as follows:

synchronized (Thread.currentThread()) {        Thread.currentThread().wait(timeInterval); } 

It looks like just Thread.sleep(timeInterval). Is it truth?

like image 744
gstackoverflow Avatar asked Apr 10 '14 07:04

gstackoverflow


People also ask

What is the use of currentThread method?

The currentThread() method of thread class is used to return a reference to the currently executing thread object.

What is the importance of thread synchronization?

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.

What is the purpose of synchronized statement?

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.

Why thread synchronization is important explain with an example?

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.


1 Answers

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

like image 196
Evgeniy Dorofeev Avatar answered Oct 02 '22 01:10

Evgeniy Dorofeev