質問するログイン新規登録

質問編集履歴

1

ひcねい

2017/01/09 10:35

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -1,65 +1,6 @@
1
- ###前提・実現したいこと
2
- 以下の3つのソースコードを使い、Gateに通った人数をカウントし、その人の名前を出身地を記録するプログラムを完成させたいです。
3
- 前提としてThreadを使うこと。
1
+ Thread
4
- 名前と出身地の頭文字が異なるときだけエラーメッセージが出るようにしているのですが、同じ場合でもエラーメッセージが出てしまいます。
5
- なんとか正常に動くようにしたいのですがどうすればいいでしょうか。
6
2
 
7
- ###Gateソースコード
8
- ```java
3
+ ```lang-言語名
9
- public class Gate {
4
+ public void run(){
10
- private int counter = 0;
11
- private String name = "Nobody";
12
- private String address = "Nowhere";
13
- synchronized public void pass(String name, String address) {
14
- this.counter++;
15
- this.name = name;
16
- this.address = address;
17
- this.check();
18
- }
5
+ k
19
- public String toString() {
20
- return "No." + this.counter + ": " + this.name + ", " + this.address;
21
- }
22
- private void check() {
23
- if (name.charAt(0) != address.charAt(0)) {
24
- System.out.println("***** Error! ***** " + toString());
25
- }
26
- }
27
- }
28
-
29
- ```
6
+ ```
30
- ###UserThread
31
- ```java
32
- public class UserThread extends Thread {
33
- private final Gate gate;
34
- private final String myname;
35
- private final String myaddress;
36
- public UserThread(Gate gate, String myname, String myaddress) {
37
- this.gate = gate;
38
- this.myname = myname;
39
- this.myaddress = myaddress;
40
- }
41
- public void run() {
42
- System.out.println(myname + " : START!");
43
- while(true){
44
- gate.pass(myname,myaddress);
45
- }
46
- }
47
- }
48
- ```
49
- ###Mainソースコード
50
- ```java
51
- public class Main {
52
- public static void main(String[] args) {
53
- System.out.println("Testing Gate, hit CTRL+C toexit.");
54
- Gate gate = new Gate();
55
- new UserThread(gate, "Alice" , "Alaska").start();
56
- new UserThread(gate , "Bobby" , "Bazil").start();
57
- new UserThread(gate , "Chis" , "Canada").start();
58
- new UserThread(gate , "David" , "Denmark").start();
59
- }
60
- }
61
-
62
- ```
63
- ###試したこと
64
- waitとsleepを使ってみた。
65
- けれど、プログラムがうまく書けなかった。