Synchronization:
Synchronization prevents concurrent execution of method or block that depends on same object, Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.
However, synchronization can introduce thread contention, which occurs when two or more threads try to access the same resource simultaneously and cause the Java runtime to execute one or more threads more slowly, or even suspend their execution. Starvation and livelock are forms of thread contention.
Synchronized method Example
public class Sample implements Runnable { public synchronized void print() { for (int i = 0; i <= 5; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void run() { // TODO Auto-generated method stub print(); } }
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Sample s1 = new Sample(); Sample s2 = new Sample(); Thread t1 = new Thread(s1); Thread t2 = new Thread(s1); Thread t3 = new Thread(s2); t1.setName("t1"); t2.setName("t2"); t3.setName("t3"); t1.start(); t2.start(); t3.start(); } }
Output:
t1: 0 t3: 0 t3: 1 t1: 1 t1: 2 t3: 2 t1: 3 t3: 3 t1: 4 t3: 4 t1: 5 t3: 5 t2: 0 t2: 1 t2: 2 t2: 3 t2: 4 t2: 5