by surrounding the desired lines of code with curly brackets ({}) and inserting the expression synchronized(someObject) before the opening curly.
import java.awt.Rectangle;
class MyClass {
Rectangle rect = new Rectangle(1, 1, 100, 100);
void doit() {
int x = 504;
int y = x / 3;
synchronized (rect) {
rect.width -= x;
rect.height -= y;
}
}
}
public synchronized void doStuff() {
System.out.println("synchronized");
}
is equivalent to this:
public void doStuff() {
synchronized(this) {
System.out.println("synchronized");
}
}
|