File tree Expand file tree Collapse file tree
src/main/java/com/algorithm/study/demo/thread Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .algorithm .study .demo .thread ;
2+
3+ import java .util .concurrent .TimeUnit ;
4+
5+ /**
6+ * 死锁案例
7+ *
8+ * 避免死锁:一种是加锁顺序(线程按照一定的顺序加锁);另一种是加锁时限(线程尝试获取锁的时候加上一定的时限,超过时限则放弃对该锁的请求,并释放自己占有的锁);
9+ */
10+ public class DeadlockTest {
11+ private static Object o1 =new Object ();
12+ private static Object o2 =new Object ();
13+ public static void main (String [] args ) {
14+ new Thread (){
15+ @ Override
16+ public void run () {
17+ synchronized (o1 ){
18+ System .out .println ("Thread1 get lock o1" );
19+ try {
20+ TimeUnit .SECONDS .sleep (1 );
21+ } catch (InterruptedException e ) {
22+ e .printStackTrace ();
23+ }
24+ synchronized (o2 ){
25+ System .out .println ("Thread1 get lock o2" );
26+ }
27+ System .out .println ("Thread1 end" );
28+ }
29+ }
30+ }.start ();
31+
32+
33+ new Thread (){
34+ @ Override
35+ public void run () {
36+ synchronized (o2 ){
37+ System .out .println ("Thread2 get lock o1" );
38+ try {
39+ TimeUnit .SECONDS .sleep (1 );
40+ } catch (InterruptedException e ) {
41+ e .printStackTrace ();
42+ }
43+ synchronized (o1 ){
44+ System .out .println ("Thread2 get lock o2" );
45+ }
46+ System .out .println ("Thread2 end" );
47+ }
48+ }
49+ }.start ();
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments