本文實例演示了java多線程死鎖。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package com.damlab.fz; public class deadlock { public static void main(string[] args) { resource r1 = new resource(); resource r2 = new resource(); // 每個線程都擁有r1,r2兩個對象 thread myth1 = new mythread1(r1, r2); thread myth2 = new mythread2(r1, r2); myth1.start(); myth2.start(); } } class resource { private int i; } class mythread1 extends thread { private resource r1, r2; public mythread1(resource r1, resource r2) { this .r1 = r1; this .r2 = r2; } @override public void run() { while ( true ) { // 先獲得r1的鎖,再獲得r2的鎖 synchronized (r1) { system.out.println( "1號線程獲取了r1的鎖" ); synchronized (r2) { system.out.println( "1號線程獲取了r2的鎖" ); } } } } } class mythread2 extends thread { private resource r1, r2; public mythread2(resource r1, resource r2) { this .r1 = r1; this .r2 = r2; } @override public void run() { while ( true ) { // 先獲得r2的鎖,再獲得r1的鎖 synchronized (r2) { system.out.println( "2號線程獲取了r2的鎖" ); synchronized (r1) { system.out.println( "2號線程獲取了r1的鎖" ); } } } } } |
運行結果:
希望本文所述對大家java程序設計有所幫助。
原文鏈接:https://blog.csdn.net/u013063153/article/details/49888821