-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSynchronizedCustomObjectDemo.java
55 lines (50 loc) · 1.25 KB
/
SynchronizedCustomObjectDemo.java
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
/**
* Utility to print from 0 to 5
*/
class PrintUtilExample3 {
//object to store the synchronized lock
final Object lockObject = new Object();
/**
* Function to print numbers from 0 to 5
*/
public void printNumbers() {
synchronized(lockObject) {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/**
* Thread worker
*/
class RunnableWorkerExample3 implements Runnable {
PrintUtilExample3 pu3;
public RunnableWorkerExample3(PrintUtilExample3 pu3){
this.pu3 = pu3;
}
@Override
public void run() {
pu3.printNumbers();
}
}
/**
* Main Class
*/
public class SynchronizedCustomObjectDemo {
public static void main(String[] args) {
PrintUtilExample3 pu3 = new PrintUtilExample3();
Runnable r = new RunnableWorkerExample3(pu3);
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
Thread t3 = new Thread(r);
t1.start();
t2.start();
t3.start();
}
}