-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadSync.java
More file actions
73 lines (65 loc) · 1.82 KB
/
ThreadSync.java
File metadata and controls
73 lines (65 loc) · 1.82 KB
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
package multiThreading;
public class ThreadSync {
public static void main(String[] args) throws Exception {
Incr in = new Incr();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
in.increment();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
in.increment();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
// in two loops, the value is inctemented upto 20000 times.
// it won't count upto 20000 unless it is synchronised
// i.e. if the increment method is declared synchronised, it will increment 20000 times else the value will be less than that
System.out.println("Coune: "+in.count);
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i<1000;i++){
synchronized (in){
in.display();
}
}
}
});
Thread t4 = new Thread(new Runnable(){
@Override
public void run(){
for(int i = 0; i<1000; i++){
synchronized (in){
in.display();
}
}
}
});
t3.start();
t4.start();
t3.join();
t4.join();
System.out.println("Value: "+in.val);
}
}
class Incr {
int count;
public synchronized void increment() {
count++;
}
int val;
public void display(){
val++;
}
}