关于java线程的

import java.util.Scanner;

public class Test {

	private T t = new T();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final Test test = new Test();
		final Scanner scanner = new Scanner(System.in);
		while (true) {
			System.out.println("请输入:1.启动 2.暂停 3.继续 4.重启 5.停止  6.退出程序");
			final int command = scanner.nextInt();
			if (command > 0 && command < 6) {
				test.command(command);
			} else {
				break;
			}
		}

	}

	public void command(int command) {

		switch (command) {
		case 1:
			new Thread(t).start();
			new Thread(t).start();
			break;
		case 2:
			t.setThreadCMD(ThreadCMD.RESUME);
			break;
		case 3:
			t.setThreadCMD(ThreadCMD.CONTINUE);
			break;
		case 4:
			t.setThreadCMD(ThreadCMD.STOP);
			command(1);
		case 5:
			t.setThreadCMD(ThreadCMD.STOP);
			break;
		}
	}

}

enum ThreadCMD {
	START, RESUME, CONTINUE , STOP
}

class T implements Runnable {

	private ThreadCMD threadCMD = ThreadCMD.START;

	private final Object object = new Object();

	private int count;

	@Override
	public void run() {
		try {

			while (true) {
				synchronized (object) {
					switch (threadCMD) {
					case START:
					case CONTINUE:
						count++;
						break;
					case RESUME:
						printInfo();
						object.wait();
						break;
					case STOP:
						printInfo();
						return;
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void printInfo(){
		System.out.println(Thread.currentThread().getName() + " ThreadCMD=" + threadCMD
				+ "--count=" + count);
	}

	public void setThreadCMD(ThreadCMD threadCMD) {
		synchronized (object) {
			this.threadCMD = threadCMD;
			object.notifyAll();
		}
	}

}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值