日期:2014-05-20 浏览次数:20888 次
class ControlledThread extends Thread {
public static final int SUSP=1;
public static final int STOP=2;
public static final int RUN=0;
private int state = RUN;
public synchronized void setState(int state){
this.state = state;
if(state == RUN){
notify();
}
}
public synchronized boolean checkState() {
while(state == SUSP){
try {
System.out.println(Thread.currentThread().getName() + ":wait");
wait();
}catch(InterruptedException e){
throw new RuntimeException(e.getMessage());
}
}
if(state == STOP){
return false;
}
return true;
}
}
public class MachineControlledThread extends ControlledThread {
private int count;
public void run() {
while(true){
synchronized(this) {
count++;
System.out.println(Thread.currentThread().getName()+":run "+count+" times");
}
if(!checkState()){
System.out.println(Thread.currentThread().getName()+":stop"); break;
}
}
}
public synchronized int getCount() {return count;}
public synchronized void reset() {
count=0;
System.out.println(Thread.currentThread().getName()+":reset");
}
public static void main(String[] args) {
MachineControlledThread machine = new MachineControlledThread();
machine.start();
for(int i=0;i<30;i++){
if(machine.getCount()>5) {
machine.setState(ControlledThread.SUSP);
yield();
machine.reset();
machine.setState(ControlledThread.RUN);
}
yield();
}
machine.setState(ControlledThread.STOP);
}
}