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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM