File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ package chapter4 ;
2+
3+ /**
4+ * Created by 13 on 2017/5/6.
5+ */
6+ public class DeadLock extends Thread {
7+ protected Object tool ;
8+ static Object fork1 = new Object ();
9+ static Object fork2 = new Object ();
10+
11+ public DeadLock (Object object ) {
12+ this .tool = object ;
13+
14+ if (tool == fork1 ) {
15+ this .setName ("哲学家A" );
16+ }
17+ if (tool == fork2 ) {
18+ this .setName ("哲学家B" );
19+ }
20+ }
21+
22+ public void run () {
23+ if (tool == fork1 ) {
24+ synchronized (fork1 ) {
25+ try {
26+ Thread .sleep (500 );
27+ } catch (InterruptedException e ) {
28+ e .printStackTrace ();
29+ }
30+
31+ synchronized (fork2 ) {
32+ System .out .println ("哲学家A开始吃饭了" );
33+ }
34+ }
35+ }
36+ if (tool == fork2 ) {
37+ synchronized (fork2 ) {
38+ try {
39+ Thread .sleep (500 );
40+ } catch (InterruptedException e ) {
41+ e .printStackTrace ();
42+ }
43+
44+ synchronized (fork1 ) {
45+ System .out .println ("哲学家B开始吃饭了" );
46+ }
47+ }
48+ }
49+ }
50+
51+
52+ public static void main (String args []) throws InterruptedException {
53+ DeadLock 哲学家A = new DeadLock (fork1 );
54+ DeadLock 哲学家B = new DeadLock (fork2 );
55+
56+ 哲学家A .start ();
57+ 哲学家B .start ();
58+
59+ Thread .sleep (1000 );
60+ }
61+ }
You can’t perform that action at this time.
0 commit comments