什么是 Two Phase Termination 模式

第二阶段的终止保证安全性,比如涉及对共享资源的操作。
要百分之百地确保线程结束,假设在第二个阶段出现了死循环、阻塞等异常导致无法结束。
对资源的释放时间要控制在一个可控的范围之内。
Two Phase Termination 的示例
线程停止的 Two Phase Termination
@Overridepublic void run(){try{this.chat();} catch (IOException e){e.printStackTrace();}}private void chat() throws IOException{BufferedReader bufferedReader = wrap2Reader(this.socket.getInputStream());PrintStream printStream = wrap2Print(this.socket.getOutputStream());String received;while ((received = bufferedReader.readLine()) != null){System.out.printf("client:%s-message:%s\n", clientIdentify, received);if (received.equals("quit")){write2Client(printStream, "client will close");socket.close();break;}write2Client(printStream, "Server:" + received);}}
@Overridepublic void run(){try{this.chat();} catch (IOException e){e.printStackTrace();} finally{//任务执行结束时,执行释放资源的工作this.release();}}private void release(){try{if (socket != null){socket.close();}} catch (Throwable e){//ignore}}
进程关闭的 Two Phase Termination
文章转载自Alleria Windrunner,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




