java多线程设计模式的实现对于一些刚学习萌新来说是有不少难度的,今天小编就给大家介绍一下。
Java代码
public class CountupThread extends Thread { // 计数器的值 private long counter = 0; // 已经送出终止请求则为true private volatile boolean shutdownRequested = false; // 终止请求 public void shutdownRequest() { shutdownRequested = true; interrupt(); } // 判断终求请求是否已经送出 public boolean isShutdownRequested() { return shutdownRequested; } //动作 public final void run() { try { while (!shutdownRequested) { doWork(); } } catch (InterruptedException e) {} finally { doShutdown(); } } // 作业 private void doWork() throws InterruptedException { counter++; System.out.println("doWork: counter = " + counter); Thread.sleep(500); } // 终止处理 private void doShutdown() { System.out.println("doShutdown: counter = " + counter); } }
Java代码
public class Main { public static void main(String[] args) { System.out.println("main: BEGIN"); try { CountupThread t = new CountupThread(); t.start(); Thread.sleep(10000); System.out.println("main: shutdownRequest"); t.shutdownRequest(); System.out.println("main: join"); t.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main: END"); } }
以上就是本篇文章的所有内容,还想了解更多常见问题的小伙伴就请关注本网站吧。
推荐阅读: