java的多线程学习,第五记
Posted TaylorLambert
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java的多线程学习,第五记相关的知识,希望对你有一定的参考价值。
死锁问题;
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的多线程学习,第五记的主要内容,如果未能解决你的问题,请参考以下文章