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