判斷執行緒結束和讓執行緒結束
package cn.lonecloud.Thread.study; /** * 用於迴圈1000次的執行緒 * @Title: Run1000Thread.java * @Package cn.lonecloud.Thread.study * @Description: * @author lonecloud * @date 2016年8月14日 下午11:06:07 */ public class Run1000Thread extends Thread{ @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println(i); if (this.interrupted()) {//用於判斷執行緒是否已經結束 try { throw new InterruptedException();//用於停止執行緒 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
暫停執行緒和恢復執行緒
package cn.lonecloud.Thread.study.resume; import org.apache.log4j.Logger; public class MainTest { public static Logger logger=Logger.getLogger(MainTest.class); public static void main(String[] args) throws Exception { ResumeThread thread=new ResumeThread(); thread.start(); logger.debug("開始"); thread.sleep(1000); thread.suspend();//獲取此執行緒停止 logger.debug("我是休眠"); thread.sleep(1000); thread.resume();//獲取執行緒繼續 logger.debug("我是啟動"); } }
執行緒類
package cn.lonecloud.Thread.study.resume; import org.apache.log4j.Logger; public class ResumeThread extends Thread{ public static Logger logger=Logger.getLogger(ResumeThread.class); @Override public void run() { logger.debug("開始"); System.out.println("Hello world"); } }