• 线程3-线程死锁


    1、死锁原因

    (1)死锁问题处理线程同步时需要处理
    (2)不同的线程分别占用对方需要的资源不放弃,都在等待对方先释放自己需要的同步资源,就造成了线程死锁
    (3)当线程执行完代码后,或者执行过程中发生异常时,线程会释放对象锁

    2、死锁例子

    package com.thread.test;
    //死锁问题处理线程同步时需要处理
    //不同的线程分别占用对方需要的资源不放弃,都在等待对方先释放自己需要的同步资源,就造成了线程死锁
    class DeatThreadTest implements Runnable {
        StringBuffer sbr = new StringBuffer();
        Object obj1 = new Object();
        Object obj2 = new Object();
    
        @Override
        public void run() {
            synchronized (obj1) {
                sbr.append("A");
                Thread.currentThread();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(sbr);
                synchronized (obj2) {
                    sbr.append("B");
                    System.out.println(sbr);
                }
            }
    
            synchronized (obj2) {
                sbr.append("C");
                Thread.currentThread();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(sbr);
                synchronized (obj1) {
                    sbr.append("D");
                    System.out.println(sbr);
                }
            }
        }
    
    }
    
    public class DeadThread {
    
        public static void main(String[] args) {
            DeatThreadTest dtt = new DeatThreadTest();
    
            Thread t1 = new Thread(dtt);
            Thread t2 = new Thread(dtt);
            
            t1.start();
            t2.start();
            
            //当线程1启动后,先拿到obj1的锁
            //在线程1沉睡时,这时线程2先拿到obj2的对象锁
            //此时,线程1等待线程2释放obj2的对象锁,线程2等待线程1释放obj1的对象锁,导致死锁
        }
    
    }
  • 相关阅读:
    wireshake抓包,飞秋发送信息,python
    python问题:IndentationError:expected an indented block错误解决《转》
    560. Subarray Sum Equals K
    311. Sparse Matrix Multiplication
    170. Two Sum III
    686. Repeated String Match
    463. Island Perimeter
    146. LRU Cache
    694. Number of Distinct Islands
    200. Number of Islands
  • 原文地址:https://www.cnblogs.com/fubaizhaizhuren/p/5066537.html
Copyright © 2020-2023  润新知