File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * @program JavaBooks
3+ * @description: 死锁的模拟
4+ * @author: mf
5+ * @create: 2020/01/09 13:57
6+ */
7+
8+
9+ import java .util .concurrent .ExecutorService ;
10+ import java .util .concurrent .Executors ;
11+
12+ /**
13+ * 用线程池模拟,比较方便一些
14+ */
15+ public class T31 {
16+
17+ private static Object res1 = new Object (); // 资源1
18+
19+ private static Object res2 = new Object (); // 资源2
20+
21+ public void m1 () {
22+ synchronized (res1 ) {
23+ // 占用res1的锁
24+ System .out .println (Thread .currentThread ().getName () + " get res1" );
25+ try {
26+ Thread .sleep (1000 ); // 延时一会,等待m2的方法占用res2
27+ } catch (InterruptedException e ) {
28+ e .printStackTrace ();
29+ }
30+ System .out .println ("waiting get res2" );
31+ synchronized (res2 ) {
32+ System .out .println (Thread .currentThread ().getName () + " get res2" );
33+ }
34+ }
35+ }
36+
37+ public void m2 () {
38+ synchronized (res2 ) {
39+ // 占用res2的锁
40+ System .out .println (Thread .currentThread ().getName () + " get res2" );
41+ try {
42+ Thread .sleep (1000 ); //
43+ } catch (InterruptedException e ) {
44+ e .printStackTrace ();
45+ }
46+ System .out .println ("waiting get res1" );
47+ synchronized (res1 ) {
48+ System .out .println (Thread .currentThread ().getName () + " get res1" );
49+ }
50+ }
51+ }
52+
53+ public static void main (String [] args ) {
54+ T31 t31 = new T31 ();
55+ ExecutorService service = Executors .newCachedThreadPool ();
56+ service .execute (() -> t31 .m1 ());
57+ service .execute (() -> t31 .m2 ());
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments