回答編集履歴
1
Thread 版を追加
answer
CHANGED
@@ -54,4 +54,61 @@
|
|
54
54
|
while(System.in.read() != target);
|
55
55
|
}
|
56
56
|
}
|
57
|
+
```
|
58
|
+
|
59
|
+
別スレッドで非同期処理をということですが, ネタとしては意味が無いように思います.
|
60
|
+
どちらかからの課題なのでしょうか.
|
61
|
+
```java
|
62
|
+
import java.io.IOException;
|
63
|
+
import java.util.Random;
|
64
|
+
|
65
|
+
class RandomTimer extends Thread {
|
66
|
+
private long wait;
|
67
|
+
private int targetCode;
|
68
|
+
private long reponseTime;
|
69
|
+
RandomTimer(int waitmax, int targetCode) {
|
70
|
+
Random random = new Random();
|
71
|
+
wait = random.nextInt(waitmax);
|
72
|
+
this.targetCode = targetCode;
|
73
|
+
}
|
74
|
+
public void run() {
|
75
|
+
try {
|
76
|
+
waitTarget(targetCode);
|
77
|
+
Thread.sleep(wait);
|
78
|
+
clearStdIn();
|
79
|
+
System.out.println("*");
|
80
|
+
long startTime = System.currentTimeMillis();
|
81
|
+
waitTarget(targetCode);
|
82
|
+
reponseTime = System.currentTimeMillis() - startTime;
|
83
|
+
} catch (IOException | InterruptedException e) {
|
84
|
+
e.printStackTrace();
|
85
|
+
}
|
86
|
+
}
|
87
|
+
public long getReponseTime() {
|
88
|
+
return reponseTime;
|
89
|
+
}
|
90
|
+
//標準入力のゴミを削除
|
91
|
+
void clearStdIn() throws IOException {
|
92
|
+
while(System.in.available() != 0) System.in.read();
|
93
|
+
}
|
94
|
+
//標準入力から targetCode が入力されるまで待つ
|
95
|
+
void waitTarget(int targetCode) throws IOException {
|
96
|
+
while(System.in.read() != targetCode);
|
97
|
+
}
|
98
|
+
}
|
99
|
+
public class Quickpress {
|
100
|
+
public static void main(String[] args) throws IOException, InterruptedException {
|
101
|
+
int targetCode = getBr();
|
102
|
+
System.out.println("Hit enter to start:");
|
103
|
+
RandomTimer randomTimer = new RandomTimer(5000, targetCode);
|
104
|
+
randomTimer.start();
|
105
|
+
randomTimer.join();
|
106
|
+
System.out.println("タイム: "+randomTimer.getReponseTime()+ "[ms]");
|
107
|
+
}
|
108
|
+
//改行コードを取得
|
109
|
+
static int getBr() {
|
110
|
+
String br = System.getProperty("line.separator");
|
111
|
+
return br.getBytes()[0];
|
112
|
+
}
|
113
|
+
}
|
57
114
|
```
|