ITeye博客

实现线程的stop,suspend和resume方法

beston · 2014-03-28 11:15 · Java · 多线程 · 编程语言 · Markdown

Thread的stop,suspend和resume方法不安全,这里使用标识变量,wait和notifyAll实现线程的挂起,恢复和停止.

/**************************************************************************************** 
 Copyright © 2014 Your Company/Org. All rights reserved.<br> 
 Reproduction or transmission in whole or in part, in any form or<br>
 by any means, electronic, mechanical or otherwise, is prohibited<br>
 without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.beston.concurrency.thread;

/**
 * @ClassName: ThreadCotronl
 * @Description: 线程控制,实现线程的suspend,resume,stop
 * @author beston
 * @date 2014年3月27日 下午5:58:19
 * @version v1.0
 * 
 */
public class ThreadCotronl {
	public static void main(String[] args) throws InterruptedException{
		SuspendResumeStop srs = new SuspendResumeStop();
		Thread t = new Thread(srs);		
		t.start();
		Thread.sleep(2000);
		
		srs.suspend();
		System.out.println("线程挂起。。。。。。");
		Thread.sleep(2000);
		
		//线程恢复
		srs.resume();
		
		Thread.sleep(2000);
	
		
		srs.stop();
		System.out.println("线程停止。。。。。。");	
	}
}
class SuspendResumeStop implements Runnable{
	private boolean paused = false;
	private volatile boolean stop = false;
	private final Object LOCK = new Object();

	public void run() {
		while (!stop) {
			synchronized (LOCK) {
				if (paused) {
					try {
						LOCK.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					//业务代码
					System.out.println("线程执行中。。。。。。");
					try {
						Thread.sleep(300);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			
		}
	}

	public void suspend() {
		synchronized (LOCK) {
			paused = true;
			LOCK.notifyAll();
		}
	}

	public void resume() {
		synchronized (LOCK) {
			paused = false;
			LOCK.notifyAll();
		}
	}
	
	public void stop(){
		stop = true;
	}
}

 效果:

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程挂起。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程停止。。。。。。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。