java中线程死锁实例

来源:互联网 发布:日本旅游多少钱 知乎 编辑:程序博客网 时间:2024/05/17 21:38
java线程死锁问题是一个很头疼的问题,那么今天就举一个小例子:
package com.cai;
public class testDemo2 {
 public static void main(String[] args) throws InterruptedException {
  testThread t1 = new testThread(true);
  testThread t2 = new testThread(false);
  Thread th = new Thread(t1);  
  Thread th2 = new Thread(t2);
  th.start();  
  th2.start();
 }
}
class myLock{
 public static final Object lock1 = new Object();
 public static final Object lock2 = new Object();
}
class testThread implements Runnable{
 private boolean flag; 
 testThread(boolean flag){
  this.flag=flag;
 }
 public void run() {
  if(flag){
   while(true){
   synchronized (myLock.lock1) {
    System.out.println(Thread.currentThread().getName()+"lock1");
    synchronized (myLock.lock2) {
     System.out.println(Thread.currentThread().getName()+"lock2");
    }
   }}
  }else{
   while(true){
   synchronized (myLock.lock2) {
    System.out.println(Thread.currentThread().getName()+"lock2");
    synchronized (myLock.lock1) {
     System.out.println(Thread.currentThread().getName()+"lock1");
    }
   }
  }
  
 }
 }
}
注意:
当我们嵌套使用同步代码时,不同的锁进行嵌套很容易形成死锁。在main方法中创建2个线程th,th2,将我们封装的目标t1,t2分别传入线程中,此时th进入获取lock1的所,而th2进入时获取lock2的锁,t1需要T2的锁,t2需要t1的锁,所以2个互不相让,产生了死锁现象。
1 0
原创粉丝点击