最简单的死锁代码示例

死锁(DeadLock):多个进程/线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放。由于进程/线程被无限期地阻塞,因此程序不可能正常终止。

package fengluo.idea;

/**
 * @Author: fengluo
 * @Date: 2023/9/17 1:02
 */
public class Test {

    private static final Object resource1 = new Object();
    private static final Object resource2 = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (resource1) {
                System.out.println(Thread.currentThread().getName() + "拿到资源1");
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "想拿到资源2,等待中");
                    synchronized (resource2) {
                        System.out.println(Thread.currentThread().getName() + "拿到资源2");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "线程A").start();

        new Thread(() -> {
            synchronized (resource2) {
                System.out.println(Thread.currentThread().getName() + "拿到资源2");
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "想拿到资源1,等待中");
                    synchronized (resource1) {
                        System.out.println(Thread.currentThread().getName() + "拿到资源1");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "线程B").start();
    }

}

你可能感兴趣的:(java,开发语言)