質問編集履歴

1

ひcねい

2017/01/09 10:35

投稿

退会済みユーザー
test CHANGED
File without changes
test CHANGED
@@ -1,129 +1,11 @@
1
- ###前提・実現したいこと
2
-
3
- 以下の3つのソースコードを使い、Gateに通った人数をカウントし、その人の名前を出身地を記録するプログラムを完成させたいです。
4
-
5
- 前提としてThreadを使うこと。
1
+ Thread
6
-
7
- 名前と出身地の頭文字が異なるときだけエラーメッセージが出るようにしているのですが、同じ場合でもエラーメッセージが出てしまいます。
8
-
9
- なんとか正常に動くようにしたいのですがどうすればいいでしょうか。
10
2
 
11
3
 
12
4
 
13
- ###Gateソースコード
5
+ ```lang-言語名
14
6
 
15
- ```java
7
+ public void run(){
16
8
 
17
- public class Gate {
18
-
19
- private int counter = 0;
20
-
21
- private String name = "Nobody";
22
-
23
- private String address = "Nowhere";
24
-
25
- synchronized public void pass(String name, String address) {
26
-
27
- this.counter++;
28
-
29
- this.name = name;
30
-
31
- this.address = address;
32
-
33
- this.check();
34
-
35
- }
9
+ k
36
-
37
- public String toString() {
38
-
39
- return "No." + this.counter + ": " + this.name + ", " + this.address;
40
-
41
- }
42
-
43
- private void check() {
44
-
45
- if (name.charAt(0) != address.charAt(0)) {
46
-
47
- System.out.println("***** Error! ***** " + toString());
48
-
49
- }
50
-
51
- }
52
-
53
- }
54
-
55
-
56
10
 
57
11
  ```
58
-
59
- ###UserThread
60
-
61
- ```java
62
-
63
- public class UserThread extends Thread {
64
-
65
- private final Gate gate;
66
-
67
- private final String myname;
68
-
69
- private final String myaddress;
70
-
71
- public UserThread(Gate gate, String myname, String myaddress) {
72
-
73
- this.gate = gate;
74
-
75
- this.myname = myname;
76
-
77
- this.myaddress = myaddress;
78
-
79
- }
80
-
81
- public void run() {
82
-
83
- System.out.println(myname + " : START!");
84
-
85
- while(true){
86
-
87
- gate.pass(myname,myaddress);
88
-
89
- }
90
-
91
- }
92
-
93
- }
94
-
95
- ```
96
-
97
- ###Mainソースコード
98
-
99
- ```java
100
-
101
- public class Main {
102
-
103
- public static void main(String[] args) {
104
-
105
- System.out.println("Testing Gate, hit CTRL+C toexit.");
106
-
107
- Gate gate = new Gate();
108
-
109
- new UserThread(gate, "Alice" , "Alaska").start();
110
-
111
- new UserThread(gate , "Bobby" , "Bazil").start();
112
-
113
- new UserThread(gate , "Chis" , "Canada").start();
114
-
115
- new UserThread(gate , "David" , "Denmark").start();
116
-
117
- }
118
-
119
- }
120
-
121
-
122
-
123
- ```
124
-
125
- ###試したこと
126
-
127
- waitとsleepを使ってみた。
128
-
129
- けれど、プログラムがうまく書けなかった。