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

本文介绍了一种使用标识变量、wait和notifyAll方法实现线程挂起、恢复和停止的方法。通过一个具体示例展示了如何避免使用Thread类的stop、suspend和resume等不安全的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 效果:

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程挂起。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程执行中。。。。。。

线程停止。。。。。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值