java Thread 停止 开始 暂停

1,写了一个小程序:

public class TestThread {

	public static void main(String[] args) {
		Thread1 t = new Thread1();
		Thread c = new Control(t);
		t.setSleep(true);
		c.setDaemon(true);
		
		t.start();
		c.start();
		System.out.println("You can input 'g' and 'Enter' to start your job.");
		System.out.println("You can input 'w' and 'Enter' to let your job to wait...");
		System.out.println("You can input 's' and 'Enter' to finish your job.");
	}
}
class Thread1 extends Thread {
	private boolean isSleep = true;
	private boolean isStop = false;
	
	public void run() {
		while(!isStop) {
			if(isSleep) {
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("Thread: "+Thread.currentThread().getName() + " do someting.");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("Thread: "+Thread.currentThread().getName() + " finished.");
	}
	
	public void setSleep(boolean sleep) {
		this.isSleep = sleep;
	}
	public void setStop(boolean stop) {
		this.isStop = stop;
	}
}
class Control extends Thread {
	private Thread1 t;
	public Control(Thread1 t) {
		this.t = t;
	}
	
	public void run() {
		while(true) {
			int r=0;
			try {
				r=System.in.read();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(r == 'g') {
				t.setSleep(false);
			} else if(r == 'w') {
				t.setSleep(true);
			} else if(r == 's') {
				t.setStop(true);
			}
		}
	}
}

 

程序说明:
1,刚开始程序的等待的。
2,你输入‘g’回车后会运行。
3,你输入‘w’回车后会再次等待。
4,再次输入‘g’回车后又会运行。
5,输入‘s'回车,会终止程序。

6,这里将控制线程设置成了Deamon的形式,因为线程t由线程c控制可以终止,而线程c始终无法终止,所以把它设置为后台线程,当让控制的线程t退出时,所有的前台线程都结束了,这样线程c就可以自动退出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值