-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSynchronizedMethodDemo.java
51 lines (47 loc) · 1.06 KB
/
SynchronizedMethodDemo.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
/**
* Utility to print numbers from 0 to 5
*/
class PrintUtil {
/**
* Function to print numbers from 0 to 5
*/
public synchronized void printNumbers() {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
//simulates delay
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* Thread worker
*/
class RunnableWorker implements Runnable {
PrintUtil pu;
public RunnableWorker(PrintUtil pu) {
this.pu = pu;
}
@Override
public void run() {
pu.printNumbers();
}
}
/**
* Main Class
*/
public class SynchronizedMethodDemo {
public static void main(String[] args) {
PrintUtil pu = new PrintUtil();
Runnable r = new RunnableWorker(pu);
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
Thread t3 = new Thread(r);
t1.start();
t2.start();
t3.start();
}
}