回答編集履歴

1

Thread 版を追加

2019/06/09 06:08

投稿

jimbe
jimbe

スコア12659

test CHANGED
@@ -111,3 +111,117 @@
111
111
  }
112
112
 
113
113
  ```
114
+
115
+
116
+
117
+ 別スレッドで非同期処理をということですが, ネタとしては意味が無いように思います.
118
+
119
+ どちらかからの課題なのでしょうか.
120
+
121
+ ```java
122
+
123
+ import java.io.IOException;
124
+
125
+ import java.util.Random;
126
+
127
+
128
+
129
+ class RandomTimer extends Thread {
130
+
131
+ private long wait;
132
+
133
+ private int targetCode;
134
+
135
+ private long reponseTime;
136
+
137
+ RandomTimer(int waitmax, int targetCode) {
138
+
139
+ Random random = new Random();
140
+
141
+ wait = random.nextInt(waitmax);
142
+
143
+ this.targetCode = targetCode;
144
+
145
+ }
146
+
147
+ public void run() {
148
+
149
+ try {
150
+
151
+ waitTarget(targetCode);
152
+
153
+ Thread.sleep(wait);
154
+
155
+ clearStdIn();
156
+
157
+ System.out.println("*");
158
+
159
+ long startTime = System.currentTimeMillis();
160
+
161
+ waitTarget(targetCode);
162
+
163
+ reponseTime = System.currentTimeMillis() - startTime;
164
+
165
+ } catch (IOException | InterruptedException e) {
166
+
167
+ e.printStackTrace();
168
+
169
+ }
170
+
171
+ }
172
+
173
+ public long getReponseTime() {
174
+
175
+ return reponseTime;
176
+
177
+ }
178
+
179
+ //標準入力のゴミを削除
180
+
181
+ void clearStdIn() throws IOException {
182
+
183
+ while(System.in.available() != 0) System.in.read();
184
+
185
+ }
186
+
187
+ //標準入力から targetCode が入力されるまで待つ
188
+
189
+ void waitTarget(int targetCode) throws IOException {
190
+
191
+ while(System.in.read() != targetCode);
192
+
193
+ }
194
+
195
+ }
196
+
197
+ public class Quickpress {
198
+
199
+ public static void main(String[] args) throws IOException, InterruptedException {
200
+
201
+ int targetCode = getBr();
202
+
203
+ System.out.println("Hit enter to start:");
204
+
205
+ RandomTimer randomTimer = new RandomTimer(5000, targetCode);
206
+
207
+ randomTimer.start();
208
+
209
+ randomTimer.join();
210
+
211
+ System.out.println("タイム: "+randomTimer.getReponseTime()+ "[ms]");
212
+
213
+ }
214
+
215
+ //改行コードを取得
216
+
217
+ static int getBr() {
218
+
219
+ String br = System.getProperty("line.separator");
220
+
221
+ return br.getBytes()[0];
222
+
223
+ }
224
+
225
+ }
226
+
227
+ ```