黑马程序员技术交流社区
标题: java多线程之实现死锁 [打印本页]
作者: kingmask 时间: 2016-4-27 00:04
标题: java多线程之实现死锁
5.实现死锁:
实现死锁的原理是两个进行同时进行时一个进程占用了另一个进程必须的资源而另一个进程却拿着此进程的必须资源,就这样两个进行相互索要资源,造成两个进程相互等待的状态
package com.itheima;
public class 实现死锁 {
public static void main(String[]args) {
DeadLock deadLock1=new DeadLock(true);
DeadLock deadLock2=new DeadLock(false);
Thread t1=new Thread(deadLock1,"一" );
Thread t2=new Thread(deadLock2,"二" );
t1.start();
t2.start();
}
}
class DeadLock implements Runnable {
static Integer A = 1;//这里需要一个对象
static Integer B = 2;
private boolean flag;
public DeadLock(){};
public DeadLock(boolean flag){
// TODO Auto-generated constructor stub
super();
this.flag = flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
if (flag) {
synchronized (String.class) {
System.out.println("线程:" + Thread.currentThread().getName()
+ "拿到了A锁");
synchronized (Integer.class) {
System.out.println("线程:"
+ Thread.currentThread().getName()+ "拿到了B锁");
}
}
} else {
synchronized (Integer.class) {
System.out.println("线程:" + Thread.currentThread().getName()
+ "拿到了B锁");
synchronized (String.class) {
System.out.println("线程:"
+ Thread.currentThread().getName()+ "拿到了A锁");
}
}
}
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |