Java多线程推荐使用的停止方法和暂停方法
判断线程结束和让线程结束
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"); } }