服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

一个死锁的例子

一个死锁的例子

public class anotherdeadlock {
  public static void main(string[] args) {
    final object resource1 = "resource1";
    final object resource2 = "resource2";
    // t1 tries to lock resource1 then resource2
    thread t1 = new thread() {
      public void run() {
        // lock resource 1
        synchronized (resource1) {
          system.out.println("thread 1: locked resource 1");

          try {
            thread.sleep(50);
          catch (interruptedexception 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(50);
          catch (interruptedexception e) {
          }

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

    // if all goes as planned, deadlock will occur,
    // and the program will never exit.
    t1.start();
    t2.start();
  }
}

扫描关注微信公众号