死锁

作者: 史小猿 | 来源:发表于2018-10-26 16:35 被阅读12次
    • 线程饥饿死锁
    public class ThreadDeadLock {
        ExecutorService exec = Executors.newSingleThreadExecutor();
        
        /**
         * 该任务会提交另外一个任务到线程池,并且等待任务的执行结果
         * @author bh
         */
        public class RenderPageTask implements Callable<String>{
            @Override
            public String call() throws Exception {
                System.out.println("RenderPageTask 依赖LoadFileTask任务返回的结果...");
                Future<String> header,footer;
                header = exec.submit(new LoadFileTask("header.html"));
                footer = exec.submit(new LoadFileTask("footer.html"));
                String page = renderBody();
                return header.get()+page+footer.get();
            }
            
            public String renderBody(){
                return "render body is ok.";
            }
        }
        
        public static void main(String[] args) {
            ThreadDeadLock lock = new ThreadDeadLock();
            Future<String> result = lock.exec.submit(lock.new RenderPageTask());
            try {
                System.out.println("last result:"+result.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }finally{
                lock.exec.shutdown();
            }
        }
    }
    
    
    
     
    class LoadFileTask implements Callable<String> {
        private String fileName;
        public LoadFileTask(String fileName){
            this.fileName = fileName;
        }
        
        @Override
        public String call() throws Exception {
            System.out.println("LoadFileTask execute call...");
            return fileName;
        }
    }
    
    • 锁顺序死锁



    • 动态锁顺序死锁




      通过锁顺序来避免死锁



    避免死锁

    相关文章

      网友评论

          本文标题:死锁

          本文链接:https://www.haomeiwen.com/subject/fmaktqtx.html