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

質問編集履歴

2

問題集の内容であることを追記

2020/04/29 12:18

投稿

kazu0630
kazu0630

スコア26

title CHANGED
File without changes
body CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  showメソッドの排他制御が原因でデッドロックになっているということまでは分かっているのですが、排他制御についての理解が乏しく、なぜデッドロックになっているのかが分かっておりません。
6
6
 
7
-
7
+ 以下問題集の内容抜粋
8
8
  ```Java
9
9
  public class Test {
10
10
 

1

コードの修正

2020/04/29 12:18

投稿

kazu0630
kazu0630

スコア26

title CHANGED
File without changes
body CHANGED
@@ -6,45 +6,45 @@
6
6
 
7
7
 
8
8
  ```Java
9
- 1 package deadlock;
10
- 2
11
- 3 public class Test {
9
+ public class Test {
12
- 4
13
- 5 public static void main(String[] args) {
14
- 6 CountThread c1 = new CountThread();
15
- 7 CountThread c2 = new CountThread();
16
- 8 c1.setCountThread(c2);
17
- 9 c2.setCountThread(c1);
18
- 10 c1.start();
19
- 11 c2.start();
20
- 12 }
21
- 13 }
22
- 14
23
- 15 class CountThread extends Thread {
24
- 16 CountThread c;
25
- 17 int i = 0;
26
- 18
27
- 19 public void setCountThread(CountThread c) {
28
- 20 this.c = c;
29
- 21 }
30
- 22
31
- 23 public synchronized void display(CountThread c) {
32
- 24 try {
33
- 25 Thread.sleep(10);
34
- 26 c.show();
35
- 27 } catch (InterruptedException e) {
36
- 28
37
- 29 }
38
- 30 }
39
- 31
40
- 32 public synchronized void show() {
41
- 33 System.out.println(c.getName());
42
- 34 }
43
- 35
44
- 36 public void run() {
45
- 37 display(c);
46
- 38 }
47
- 39
48
- 40 }
49
10
 
11
+ public static void main(String[] args) {
12
+ // TODO 自動生成されたメソッド・スタブ
13
+
14
+ CountThread c1 = new CountThread();
15
+ CountThread c2 = new CountThread();
16
+ c1.setCountThread(c2);
17
+ c2.setCountThread(c1);
18
+ c1.start();
19
+ c2.start();
20
+ }
21
+ }
22
+
23
+ class CountThread extends Thread {
24
+ CountThread c;
25
+ int i = 0;
26
+
27
+ public void setCountThread(CountThread c) {
28
+ this.c = c;
29
+ }
30
+
31
+ public synchronized void display(CountThread c) {
32
+ try {
33
+ Thread.sleep(10);
34
+ c.show();
35
+ } catch (InterruptedException e) {
36
+
37
+ }
38
+ }
39
+
40
+ public synchronized void show() {
41
+ System.out.println(c.getName());
42
+ }
43
+
44
+ public void run() {
45
+ display(c);
46
+ }
47
+
48
+ }
49
+
50
50
  ```