服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

[java100例]066、线程控制

/**
 * <p>title: 线程控制</p>
 * <p>description: 实现对线程的控制,中断、挂起、恢复、停止</p>
 * <p>copyright: copyright (c) 2003</p>
 * <p>filename: threadctrl.java</p>
 * @version 1.0
 */
public class threadctrl{
  public static void main(string [] main){
     new threadctrl();
  }
/**
 *<br>方法说明:构造器,控制其它线程
 *<br>输入参数:
 *<br>返回类型:
 */
  threadctrl(){
    try{
     thread tm = thread.currentthread();
     threadchild td = new threadchild();
     td.start();
     tm.sleep(500);
     system.out.println("interrupt child thread");
     td.interrupt();


     system.out.println("let child thread wait!");
     //td.wait();
     //td.suspend();
     tm.sleep(1000);


     system.out.println("let child thread working");
     td.fauxresume();
     //td.resume();
     tm.sleep(1000);
     td.runflag = false;
     system.out.println("main over..............");
   }catch(interruptedexception ie){
     system.out.println("inter main::"+ie);
   }catch(exception e){
     system.out.println("main::"+e);
   }
  }


}
/**
 *<br>类说明:被控线程类
 */
  class threadchild extends thread {
    boolean runflag = true;
    boolean suspended = true;
    threadchild(){
    }
    public synchronized void fauxresume(){
      suspended = false;
      notify();
    }
    public  void run(){
      while(runflag){
        system.out.println("i am working..............");
        try{
          sleep(1000);
        }catch(interruptedexception e){
          system.out.println("sleep::"+e);
        }
       synchronized(this){
        try{
          if(suspended)
           wait();
        }catch(interruptedexception e){
          system.out.println("wait::"+e);
        }
       }
      }
      system.out.println("thread over...........");
    }
  }

扫描关注微信公众号