码迷,mamicode.com
首页 > 编程语言 > 详细

java的多线程学习,第五记

时间:2018-12-21 18:09:50      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:size   []   art   线程   obj   stack   col   public   顺序   

 死锁问题;

public class DeadLock {

    //锁的嵌套 会出现死锁
    //1 尽量不要去写锁嵌套
    //2

    private static Object locka = new Object();
    private static Object lockb = new Object();

    public static void main(String[] args) {
        new DeadLock().deadLock();
    }

    private void deadLock() {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (locka){
                    try {
                        System.out.println(Thread.currentThread().getName()+"获取A锁 ing~!");
                        Thread.sleep(500);
                        System.out.println(Thread.currentThread().getName()+"睡眠 500ms!");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"需要B锁!!!");
                    synchronized (lockb){
                        System.out.println(Thread.currentThread().getName()+"B锁中!!!");
                    }
                }
            }
        },"thread1");

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lockb){
                    try {
                        System.out.println(Thread.currentThread().getName()+"获取B锁 ing~!");
                        Thread.sleep(500);
                        System.out.println(Thread.currentThread().getName()+"睡眠 400ms!");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"需要A锁!!");
                    synchronized (locka){
                        System.out.println(Thread.currentThread().getName()+"A锁中!");
                    }
                }
            }
        },"thread2");

        thread1.start();
        thread2.start();
    }

}
锁的嵌套 会出现死锁
1 尽量不要去写锁嵌套
2 锁嵌套的顺序
3 引入超时机制

java的多线程学习,第五记

标签:size   []   art   线程   obj   stack   col   public   顺序   

原文地址:https://www.cnblogs.com/fuckingPangzi/p/10157225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!