死锁的简单示例

死锁1---通过sleep实现

public class Main implements Runnable {

    public int idx;
    public static Object[] objs = new Object[] {new Object(), new Object()};
    
    public Main(int idx) {this.idx = idx&1;}
    
    public void run() {
        synchronized(objs[idx]) {
            System.out.println(Thread.currentThread().getName() 
                    + " is now getting [" + idx +"]");
            try {
                Thread.sleep(1000);
            } catch(Exception e) {
                e.printStackTrace();
            }
            synchronized(objs[idx^1]) {
                System.out.println(Thread.currentThread().getName() 
                        + " is now getting [" + (idx^1) +"]");
            }
        }
    }
    
    public static void main(String[] args) {
        new Thread(new Main(0)).start();
        new Thread(new Main(1)).start();
    }
    
}

死锁2---SignleThreadExecutor负线程等待子线程

import java.util.concurrent.*;

public class Main {
    ExecutorService exec = Executors.newSingleThreadExecutor();

    public class A implements Callable<String> {
        public String call() throws Exception {
            return "yo";
        }
    }

    public class B implements Callable<String> {
        public String call() throws Exception {
            return exec.submit(new A()).get();
        }
    }
    
    public static void main(String[] args) throws Exception {
        Main main = new Main();
        Main.B mb = main.new B();
        Future<?> future = main.exec.submit(mb);
        System.out.println(future.get());
        System.out.println("are u ok???");
    }
}

死锁3---不使用sleep实现

其实和版本1差不多,样例来自深入理解JVM

猜你喜欢

转载自www.cnblogs.com/caturra/p/10952697.html