zoukankan      html  css  js  c++  java
  • 线程死锁

    package com.atguigu.java1;
    
    /**
     * 演示线程的死锁问题
     *
     * 1.死锁的理解:不同的线程分别占用对方需要的同步资源不放弃,
     * 都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
     *
     * 2.说明:
     * 1)出现死锁后,不会出现异常,不会出现提示,只是所有的线程都处于阻塞状态,无法继续
     * 2)我们使用同步时,要避免出现死锁。
     *
     * @author shkstart
     * @create 2019-02-15 下午 3:20
     */
    public class ThreadTest {
    
        public static void main(String[] args) {
    
            StringBuffer s1 = new StringBuffer();
            StringBuffer s2 = new StringBuffer();
    
    
            new Thread(){
                @Override
                public void run() {
    
                    synchronized (s1){
    
                        s1.append("a");
                        s2.append("1");
    
                        try {
                            Thread.sleep(100);  //下面的new Thread(new Runnable()极大可能执行
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
    
                        synchronized (s2){
                            s1.append("b");
                            s2.append("2");
    
                            System.out.println(s1);
                            System.out.println(s2);
                        }
    
    
                    }
    
                }
            }.start();
    
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (s2){
    
                        s1.append("c");
                        s2.append("3");
    
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                        synchronized (s1){
                            s1.append("d");
                            s2.append("4");
    
                            System.out.println(s1);
                            System.out.println(s2);
                        }
    
    
                    }
    
    
    
                }
            }).start();
    
    
        }
    
    
    }
    

    情况一:正确

    ab
    12
    abcd
    1234
    
  • 相关阅读:
    前进篇
    2014年12月14日记
    转载了两篇别人写的话语
    想好了,也决定了
    活着
    c#字典排序
    插值转向
    unity手游使用terrian注意事项
    委托delegate 泛型委托action<> 返回值泛型委托Func<> 匿名方法 lambda表达式 的理解
    推荐博客关于uniy
  • 原文地址:https://www.cnblogs.com/fenxiangyuan/p/14416153.html
Copyright © 2011-2022 走看看