个性化阅读
专注于IT技术分析

Java线程死锁

Java中的死锁是多线程的一部分。当线程正在等待由另一个线程获取的对象锁而第二个线程正在等待由第一个线程获取的对象锁时, 可能会发生死锁。由于两个线程都在互相等待释放锁, 因此该条件称为死锁。

Java中的Java线程死锁

Java中的死锁示例

public class TestDeadlockExample1 {
  public static void main(String[] args) {
    final String resource1 = "ratan jaiswal";
    final String resource2 = "vimal jaiswal";
    // t1 tries to lock resource1 then resource2
    Thread t1 = new Thread() {
      public void run() {
          synchronized (resource1) {
           System.out.println("Thread 1: locked resource 1");

           try { Thread.sleep(100);} catch (Exception e) {}

           synchronized (resource2) {
            System.out.println("Thread 1: locked resource 2");
           }
         }
      }
    };

    // t2 tries to lock resource2 then resource1
    Thread t2 = new Thread() {
      public void run() {
        synchronized (resource2) {
          System.out.println("Thread 2: locked resource 2");

          try { Thread.sleep(100);} catch (Exception e) {}

          synchronized (resource1) {
            System.out.println("Thread 2: locked resource 1");
          }
        }
      }
    };

    
    t1.start();
    t2.start();
  }
}
Output: Thread 1: locked resource 1
        Thread 2: locked resource 2
赞(0)
未经允许不得转载:srcmini » Java线程死锁

评论 抢沙发

评论前必须登录!