WEB开发网
开发学院软件开发Java 多线程设计模式--two-phase termination 阅读

多线程设计模式--two-phase termination

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示:two-phase termination 等待线程执行终止处理再结束线程 Java代码publicclassCountupThreadextendsThread{//计数器的值privatelongcounter=0;//已经送出终止请求则为trueprivatevolatilebooleanshutdownR

two-phase termination 等待线程执行终止处理再结束线程

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");  
  } 

Tags:线程 设计模式 two

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接