Java死锁是指两个或多个线程在执行过程中,因争夺资源而造成的一种相互等待的现象,当线程处于这种状态时,它们无法继续执行,除非其他线程释放它们正在等待的资源,下面是一个Java死锁的简单例子:
1、创建两个线程类ThreadA
和ThreadB
,分别继承Thread
类。
class ThreadA extends Thread { private Object lock1; private Object lock2; public ThreadA(Object lock1, Object lock2) { this.lock1 = lock1; this.lock2 = lock2; } @Override public void run() { synchronized (lock1) { System.out.println("ThreadA 获取了 lock1"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock2) { System.out.println("ThreadA 获取了 lock2"); } } } } class ThreadB extends Thread { private Object lock1; private Object lock2; public ThreadB(Object lock1, Object lock2) { this.lock1 = lock1; this.lock2 = lock2; } @Override public void run() { synchronized (lock1) { System.out.println("ThreadB 获取了 lock1"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock2) { System.out.println("ThreadB 获取了 lock2"); } } } }
2、在main
方法中创建两个对象lock1
和lock2
,并创建两个线程threadA
和threadB
,分别传入这两个对象作为参数,然后启动这两个线程。
public class DeadlockExample { public static void main(String[] args) { Object lock1 = new Object(); Object lock2 = new Object(); Thread threadA = new ThreadA(lock1, lock2); Thread threadB = new ThreadB(lock1, lock2); threadA.start(); threadB.start(); } }
3、运行程序,观察输出结果,由于线程threadA
和threadB
分别持有lock1
和lock2
的锁,且按照相同的顺序尝试获取锁,因此它们会互相等待对方释放锁,导致死锁,程序将无法继续执行。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/641723.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复