本文实例演示了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