Credits

Friday, August 13, 2010

Java's Thread Synchronization

Threads can be done in parallel, however,  a typical problem with running multiple threads is when these processes try to access the same record or variables. To resolve this conflict, synchronization is used to allow locking.

Lock of variables can be done using the synchronization method or using a synchronization block. When a thread gets into a synchronized method, it enforces locking but as soon as it leaves the block or method, unlocking is automatic allowing for other threads to get into the block or method.

Below is the sample program of thread synchronized methods.

[+/-] show/hide

/** Based on example from Sun Thread tutorial */

class Reentrant {

public synchronized void a() {
b();
System.out.println("here I am, in a()");
}
public synchronized void b() {
System.out.println("here I am, in b()");
}
}

class TestReentrant {
public static void main(String[] args) {
Reentrant r = new Reentrant();
r.a();
}
}

AddThis