- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadExampleSynchronized.java
More file actions
Latest commit
79 lines (65 loc) · 1.52 KB
/
Copy pathThreadExampleSynchronized.java
File metadata and controls
79 lines (65 loc) · 1.52 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
74
75
76
77
78
79
packageconcept.examples.threads;
classSpreadSheet {
intcell1, cell2, cell3;
intsetandGetSum(inta1, inta2, inta3) {
cell1 = a1;
sleepForSomeTime();
cell2 = a2;
sleepForSomeTime();
cell3 = a3;
sleepForSomeTime();
returncell1 + cell2 + cell3;
}
voidsleepForSomeTime() {
try {
Thread.sleep(10 * (int) (Math.random() * 100));
} catch (InterruptedExceptione) {
e.printStackTrace();
}
}
}
classSynchronizedSyntaxExample {
staticintcount;
intinstanceValue;
// others..
synchronizedvoidsynchronizedExample1() {
// All code goes here..
}
voidsynchronizedExample2() {
synchronized (this) {
// All code goes here..
}
}
synchronizedstaticintgetCount() {
returncount;
}
staticintgetCount2() {
synchronized (SynchronizedSyntaxExample.class) {
returncount;
}
}
}
publicclassThreadExampleSynchronizedimplementsRunnable {
SpreadSheetspreadSheet = newSpreadSheet();
@Override
publicvoidrun() {
for (inti = 0; i < 4; i++) {
System.out.print(spreadSheet.setandGetSum(i, i * 2, i * 3) + " ");
}
}
publicstaticvoidmain(String[] args) {
ThreadExampleSynchronizedr = newThreadExampleSynchronized();
Threadone = newThread(r);
Threadtwo = newThread(r);
one.start();
two.start();
// First UnSynchronized Run
// 0 3 6 9 12 15 18 18
// Second UnSynchronized Run
// 0 1 6 7 12 18 18 18
// Synchronized Run
// 0 0 6 6 12 12 18 18
// A static synchronized method and a non-static synchronized method
// will not block each other,
}
}