• 线程死锁问题


    一、定义

      线程死锁是指由于两个或者多个线程互相持有对方所需要的资源,导致这些线程处于等待状态,无法前往执行。当线程进入对象的synchronized代码块时,便占有了资源,直到它退出该代码块或者调用wait方法,才释放资源,在此期间,其他线程将不能进入该代码块。当线程互相持有对方所需要的资源时,会互相等待对方释放资源,如果线程都不主动释放所占有的资源,将产生死锁。

    二、实例

      

    package book.thread.deadlock;

    public class DeadLock {
      public static void main(String[] args) {
        //两个资源
        final Object resource1 = "resource1";
        final Object resource2 = "resource2";
        //第一个线程,想先占有resource1,再尝试着占有resource2
        Thread t1 = new Thread(){
          public void run(){
            //尝试占有resource1
            synchronized(resource1){
              //成功占有resource1
              System.out.println("Thread1 1:locked resource1");
              //休眠一段时间
              try {
                Thread.sleep(50);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              //尝试占有resource2,如果不能占有,该线程会一直等到
              synchronized(resource2){
                 System.out.println("Thread1 1:locked resource2");
              }
            }
          }
        };
        //第二个线程,想先占有resource2,再占有resource1
        Thread t2 = new Thread(){
          public void run(){
            //尝试占有resource2
            synchronized(resource2){
              //成功占有resource2
              System.out.println("Thread 2 :locked resource2");
              //休眠一段时间
              try {
                Thread.sleep(50);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
            //尝试占有resource1,如果不能占有,该线程会一直等到
            synchronized(resource1){
              System.out.println("Thread1 2:locked resource1");
            }
          }
        }
      };
      //启动线程
      t1.start();
      t2.start();
      }
    }

    输出结果:

    Thread 2 :locked resource2
    Thread1 1:locked resource1

    结果分析:

      线程Thread1率先占有了resource1,继续运行时需要resource2,但此时resource2却被线程Thread2占有了,因此只能等待Thread2释放resource2才能够继续运行;同时,Thread2也需要resource1,它只能等待Thread1释放resource1才能够继续运行,因此,Thread1和Thread2都处于等待状态,谁也无法继续运行,即产生了死锁。

  • 相关阅读:
    trie树(板子)
    A. Many Equal Substrings(思维)
    D2 Equalizing by Division (hard version) &&D1 Equalizing by Division (easy version) (easy version)(Codeforces Round #582 (Div. 3))
    B. Square Filling ( Educational Codeforces Round 71 (Rated for Div. 2))
    A. Creating a Character(Educational Codeforces Round 72 (Rated for Div. 2) )
    字符画 (CSU 2163 )
    The Nth Item (The 2019 Asia Nanchang First Round Online Programming Contest)
    Magic Master (The 2019 Asia Nanchang First Round Online Programming Contest)
    Fire-Fighting Hero (The 2019 Asia Nanchang First Round Online Programming Contest)
    Pangu Separates Heaven and Earth(签到题)(The 2019 Asia Nanchang First Round Online Programming Contest)
  • 原文地址:https://www.cnblogs.com/czl362326/p/5686200.html
Copyright © 2020-2023  润新知