用CompletableFuture模拟死锁

将两把锁作为参数传递给MySupplier,get方法中用两个synchronized加锁,中间等待5秒

package com.test.jvm;

import java.lang.management.ManagementFactory;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;


public class DeadLock 
{
	private static Object locker1 = new Object();
	private static Object locker2 = new Object();

    private static class MySupplier implements Supplier<Void> {
    	
    	Object locker1, locker2;
    	String threadName;

    	public MySupplier(String threadName, Object locker1, Object locker2) {
    		this.locker1 = locker1;
    		this.locker2 = locker2;
    		this.threadName = threadName;
    	}

		@Override
		public Void get() {

			Thread.currentThread().setName(threadName);

			System.out.println(threadName + " try to lock " + locker1);
			synchronized (locker1) {
				System.out.println(threadName + " locked " + locker1);
				
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				System.out.println(threadName + " try to lock" + locker2);
				synchronized (locker2) {
					System.out.println(threadName + "locked " + locker2);
				}
				System.out.println(threadName + "released " + locker2);
				
			}
			System.out.println(threadName + "released " + locker1);
			
			return null;
		}
    	
    }
    
    

    public static void main( String[] args ) {

    	String pid = ManagementFactory.getRuntimeMXBean().getName();
    	//@之前为进程ID
    	pid = pid.substring(0, pid.indexOf('@'));
    	System.out.println(pid);

    	CompletableFuture<Void> future1 = CompletableFuture.supplyAsync(new MySupplier("thread1", locker1, locker2));
    	CompletableFuture<Void> future2 = CompletableFuture.supplyAsync(new MySupplier("thread2", locker2, locker1));
    	
    	try {
			future1.get();
			future2.get();
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }
}

执行结果如下:
46012
thread2 try to lock java.lang.Object@9beb73f
thread2 locked java.lang.Object@9beb73f
thread1 try to lock java.lang.Object@7ee2a9e0
thread1 locked java.lang.Object@7ee2a9e0
thread2 try to lockjava.lang.Object@7ee2a9e0
thread1 try to lockjava.lang.Object@9beb73f

两个线程得到第一把锁后都想得到对方的锁,发生死锁。

jstack dump的结果
用CompletableFuture模拟死锁

上一篇:JAVA8给我带了什么——Optional和CompletableFuture


下一篇:Future模式之CompletableFuture