Sunday, 26 January 2020

What is Synchronization in Java

What is Synchronization in Java

Synchronization in java is the capability to control the access of multiple threads to any shared resource.


Example :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package JavaPractice;

import java.util.Date;

public class TestSynchronization {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Table obj = new Table();
  MyThread1 th1 = new MyThread1(obj, true); // true for Synchronization
  MyThread2 th2 = new MyThread2(obj, true);
  th1.start();
  th2.start();
 }

}

class Table {
 // method not Synchronization
 void printTable(int n) {
  for (int i = 1; i <= 5; i++) {
   System.out.println(n * i);
   try {
    Thread.sleep(400);
   } catch (Exception e) {
    System.out.println(e);
   }
  }

 }

 // method is Synchronization
 synchronized void printTableSynchronization(int n) {
  for (int i = 1; i <= 5; i++) {
   System.out.println(n * i);
   try {
    Thread.sleep(400);
   } catch (Exception e) {
    System.out.println(e);
   }
  }

 }
}

class MyThread1 extends Thread {
 Table t;
 boolean isCallSynchronization;

 MyThread1(Table t, boolean isCallSynchronization) {
  this.t = t;
  this.isCallSynchronization = isCallSynchronization;
 }

 public void run() {
  if (this.isCallSynchronization) {
   System.out.println(new Date());
   t.printTableSynchronization(5);
   System.out.println(new Date());
  } else {
   System.out.println(new Date());
   t.printTable(5);
   System.out.println(new Date());
  }
 }
}

class MyThread2 extends Thread {
 Table t;
 boolean isCallSynchronization;

 MyThread2(Table t, boolean isCallSynchronization) {
  this.t = t;
  this.isCallSynchronization = isCallSynchronization;
 }

 public void run() {
  if (this.isCallSynchronization) {
   System.out.println(new Date());
   t.printTableSynchronization(100);
   System.out.println(new Date());
  } else {
   System.out.println(new Date());
   t.printTable(100);
   System.out.println(new Date());
  }
 }
}

No comments:

Post a Comment