回答編集履歴

1

コード例を追記しました。

2016/04/21 07:45

投稿

argius
argius

スコア9390

test CHANGED
@@ -21,3 +21,117 @@
21
21
 
22
22
 
23
23
  の状態になります。
24
+
25
+
26
+
27
+ ---
28
+
29
+
30
+
31
+ (追記)
32
+
33
+
34
+
35
+ 上で説明しているコードを実際に書くとこんな感じです。
36
+
37
+
38
+
39
+ ```lang-java
40
+
41
+ public final class App {
42
+
43
+
44
+
45
+ public static void main(String[] args) {
46
+
47
+ Counter counter = new Counter();
48
+
49
+ CountDownThread t1 = new CountDownThread("thread 1", counter);
50
+
51
+ CountDownThread t2 = new CountDownThread("thread 2", counter);
52
+
53
+ t1.start();
54
+
55
+ t2.start();
56
+
57
+ }
58
+
59
+
60
+
61
+ }
62
+
63
+
64
+
65
+ class Counter {
66
+
67
+
68
+
69
+ private int count;
70
+
71
+
72
+
73
+ void increment() {
74
+
75
+ ++count;
76
+
77
+ }
78
+
79
+
80
+
81
+ int getCount() {
82
+
83
+ return count;
84
+
85
+ }
86
+
87
+
88
+
89
+ }
90
+
91
+
92
+
93
+ class CountDownThread extends Thread {
94
+
95
+
96
+
97
+ private String name;
98
+
99
+ private Counter counter;
100
+
101
+
102
+
103
+ public CountDownThread(String name, Counter counter) {
104
+
105
+ this.name = name;
106
+
107
+ this.counter = counter;
108
+
109
+ }
110
+
111
+
112
+
113
+ public void run() {
114
+
115
+ for (int i = 3; i >= 0; i--) {
116
+
117
+ try {
118
+
119
+ counter.increment();
120
+
121
+ sleep(1000);
122
+
123
+ } catch (InterruptedException e) {
124
+
125
+ }
126
+
127
+ System.out.println(name + " : " + i);
128
+
129
+ }
130
+
131
+ }
132
+
133
+
134
+
135
+ }
136
+
137
+ ```