public class DeadLockDemo { /** * 避免一个线程同时获得多个锁; * 避免一个线程在锁内部占有多个资源,尽量保证每个锁只占用一个资源; * 尝试使用定时锁,使用lock.tryLock(timeOut),当超时等待时当前线程不会阻塞; * 对于数据库锁,加锁和解锁必须在一个数据库连接里,否则会出现解锁失败的情况 * */ private static String demo_a = "A"; private static String demo_b = "B"; public static void main(String[] args) { deadLock(); } /** * 单一线程0,不存在资源的争夺问题 * 在线程1获取资源a后等待三秒,这时候线程2将获得b的资源,导致线程1无法继续获取b的资源, * 导致线程1的死锁,而线程2也因为线程1在一开始占据了资源b进入死锁,两个线程因为资源的 * 争夺问题,最客观的就是线程3,这时候由于线程1和线程2争夺资源,导致了后续的线程无法获 * 得任何资源,进入死锁。 */ public static void deadLock(){ Thread thread_0 = new Thread(new Runnable(){ @Override public void run() { synchronized (demo_a){ System.out.println("thread_0 get demo a"); synchronized (demo_b){ System.out.println("thread_0 get demo b"); } } } }); Thread thread_1 = new Thread(new Runnable(){ @Override public void run() { synchronized (demo_a){ System.out.println("thread_1 get demo a"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (demo_b){ System.out.println("thread_1 get demo b"); } } } }); Thread thread_2 = new Thread(new Runnable(){ @Override public void run() { synchronized (demo_b){ System.out.println("thread_2 get demo_b"); synchronized (demo_a){ System.out.println("thread_2 get demo_a"); } } } }); Thread thread_3 = new Thread(new Runnable(){ @Override public void run() { synchronized (demo_a){ System.out.println("thread_3 get demo a"); synchronized (demo_b){ System.out.println("thread_3 get demo b"); } } } }); thread_0.start(); thread_1.start(); thread_2.start(); thread_3.start(); } }
线程死锁的初步理解
最新推荐文章于 2021-04-13 20:08:53 发布