匿名构造方法 与 ShutDownHook

匿名构造方法,在任何构造方法之前被调用。这样保证我们初始化Business类时已经向队列2中插入了数据

static class Business{
         
        BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
        BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);
 
        {
            try{
                queue2.put(1);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
}


注册了一个shutdownhook,在程序异常终止时,确保serversocket被关闭。

Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(server)); 

    class ShutdownHookThread extends Thread {  
        private ServerSocket server;  
      
        public ShutdownHookThread(ServerSocket server) {  
            this.server = server;  
        }  
      
        @Override  
        public void run() {  
            try {  
                server.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                server = null;  
            }  
        }  
    }  

你可能感兴趣的:(shutdown)