a- /**
- * 死锁演示
- */
- public class DeadLock implements Runnable {
- private Object objA = new Object();
- private Object objB = new Object();//锁对象
- private boolean flag = false;
-
- // DeadLock(boolean b){
- // this.flag = b;
- // }
- @Override
- public void run() {
- // 相互嵌套是锁,可能会出现互相等待的现象导致死锁
- while(true){
- if(flag){
- synchronized(objA){//嵌套锁
- System.out.println("if A..."+Thread.currentThread().getName());
- synchronized(objB){
- System.out.println("if B..."+Thread.currentThread().getName());
- }
- flag = flag^true; //flag取反
- }
- }else{
- synchronized(objB){//嵌套锁
- System.out.println("else A..."+Thread.currentThread().getName());
- synchronized(objA){
- System.out.println("else B..."+Thread.currentThread().getName());
-
- }
- flag = flag^true; //flag取反
- }
- }
- }
-
- }
- }
复制代码
- public class DeadLockTest {
- /**
- * 用于死锁的测试
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //建立资源对象
- DeadLock d1 = new DeadLock();
- //新建两个进程
- new Thread(d1,"线程1").start();
- new Thread(d1,"线程2").start();
- }
- }
复制代码
|
|