回答編集履歴

2

編集コード

2017/05/19 03:58

投稿

shafi_bo
shafi_bo

スコア20

test CHANGED
@@ -10,4 +10,104 @@
10
10
 
11
11
 
12
12
 
13
+ 無理やりずらしてみました。
13
14
 
15
+
16
+
17
+ ```ここに言語を入力
18
+
19
+ public class StartApp extends Thread {
20
+
21
+
22
+
23
+ static int counter;
24
+
25
+ private int id;
26
+
27
+
28
+
29
+ StartApp(int id) {
30
+
31
+ this.id = id;
32
+
33
+ }
34
+
35
+
36
+
37
+ public synchronized void run() {
38
+
39
+ while (true) {
40
+
41
+ System.out.println(id + ":" + counter);
42
+
43
+ counter++;
44
+
45
+ try {
46
+
47
+ Thread.sleep(1000);
48
+
49
+ } catch (InterruptedException e) {
50
+
51
+ // TODO 自動生成された catch ブロック
52
+
53
+ e.printStackTrace();
54
+
55
+ }
56
+
57
+
58
+
59
+ }
60
+
61
+ }
62
+
63
+
64
+
65
+ public static void main(String[] args) {
66
+
67
+ // TODO Auto-generated method stub
68
+
69
+ Thread t[] = new Thread[4];
70
+
71
+ for (int i = 0; i < 4; i++) {
72
+
73
+ t[i] = new Thread(new StartApp(i));
74
+
75
+ }
76
+
77
+ try{
78
+
79
+ t[0].start();
80
+
81
+ Thread.sleep(100);
82
+
83
+ t[1].start();
84
+
85
+ Thread.sleep(100);
86
+
87
+ t[2].start();
88
+
89
+ Thread.sleep(100);
90
+
91
+ t[3].start();
92
+
93
+ Thread.sleep(100);
94
+
95
+ } catch (InterruptedException e){
96
+
97
+
98
+
99
+ }
100
+
101
+ }
102
+
103
+
104
+
105
+
106
+
107
+ ```
108
+
109
+
110
+
111
+ 各スレッドの生成を遅らせて生成を試みてみました。
112
+
113
+ 正直無理やり感がぬぐえないのとテスト回数が少ないので正しいかどうかはわかりませんが一応貼っておきます。

1

質問

2017/05/19 03:58

投稿

shafi_bo
shafi_bo

スコア20

test CHANGED
@@ -1,3 +1,13 @@
1
1
  スレッドは、一つ一つ処理速度が違います。
2
2
 
3
3
  なので、counterをアクセス時に他スレッドで足された後にアクセスするケースがズレにあたると思われます。
4
+
5
+
6
+
7
+ 逆に質問しますが、同時に[0][1][2][3]が同じ値のcounterを取得するということでいいんでしょうか?
8
+
9
+ それとも[0] = 0, [1] = 1, [2] = 2, [3] = 3, [0] = 4, [1] = 5.....といったかんじでしょうか?
10
+
11
+
12
+
13
+