[ Back | Previous | Next ]

How to synchronize a piece of code?

Package:
java.lang.*
Product:
JDK
Release:
1.0.2
Related Links:
General
General
General
General
General
General
General
General
General
Runtime
System
Comment:
When working with thread we need to incapsulate a piece so that only one thread at a time 
can work with it. What is the syntax for that code

public void myThreadExecution() 
{
    if ( x == 0 )
    {
         synchronized (this) 
         {
            getBoardPanel().detect(block, direction);
         }
    }
    else
         x = 0;
}
Another more familiar is to synchonize a method so that only one thread can invoke the method at a time.
public synchronized void myThreadExecution() 
{
    if ( x == 0 )
            getBoardPanel().detect(block, direction);
    else
         x = 0;
}
1