当然可以。以下是一个简单的Java代码示例,模拟了两个线程之间因资源竞争而产生死锁的情况:
public class DeadlockExample { private static final Object resource1 = new Object(); private static final Object resource2 = new Object(); public static void main(String[] args) { Thread thread1 = new Thread(() -> { synchronized (resource1) { System.out.println("Thread 1: 持有 resource1"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread 1: 等待 resource2"); synchronized (resource2) { System.out.println("Thread 1: 同时持有 resource1 和 resource2"); } } }); Thread thread2 = new Thread(() -> { synchronized (resource2) { System.out.println("Thread 2: 持有 resource2"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread 2: 等待 resource1"); synchronized (resource1) { System.out.println("Thread 2: 同时持有 resource1 和 resource2"); } } }); thread1.start(); thread2.start(); } }
在这个示例中,两个线程分别尝试获取resource1和resource2,然后互相等待对方释放资源,从而导致死锁的发生。