多執行緒問題

hti發表於2005-12-11
主要是holdResume()和run()這兩個方法的實現有點不太明白,不知道如何讓執行緒掛起後,重新啟動

望有朋友能指教

class Counter implements Runnable {
// You might use these constants and variables.
private final int IDLE = 0, RUNNING = 1, HOLDING = 2;

private StartResumeStopApplication application;

private int value;

// The following variable is set whenever a new thread is created. It is
// set to null within the run() method whenever the thread executing the
// run() method terminates.
private Thread myThread = null;

Thread t = new Thread(this);

private int state = IDLE;

public Counter(StartResumeStopApplication app) {
value = 0;
application = app;
}

/**
* Upon applying method begin, its counter value is reset, a new thread
* object is created and a thread is started. Subsequent calls to this
* method take no effect unless method terminate has been called.
*/
public synchronized void begin() {
// TODO: Complete the begin() method.
// Set the Counter's state to RUNNING and start a thread.
// Ensure that only a single thread is started!
value = 0;
state = RUNNING;
System.out.println("state: "+state);
t.start();
}

/**
* Upon applying method holdResume, it looks like the counter were
* suspended/resumed. This method has no effect if the counter is in state
* IDLE.
*/
public synchronized void holdResume() {
// TODO: Complete the holdResume() method.
// We have two cases here:
// - we are in the RUNNING state:
// put ourselves into the HOLDING state
// - we are in the HOLDING state:
// put ourselves into the RUNNING state
if (state == 1) {
state = HOLDING;
System.out.println("state: "+state);
}
else
if (state == 2) {
state = RUNNING;
System.out.println("state: "+state);
begin();
}

}

/**
* Upon applying method terminate, the thread is terminated. Subsequent
* calls to this method take no effect unless method begin has been called.
*/
public synchronized void terminate() {
// TODO: Complete the terminate() method.
// Terminate the thread if this Counter object is in the RUNNING state.
// In any case set the Counter object state to IDLE.
if (state == 1)
t.interrupt();

state = IDLE;
System.out.println("state: "+state);
}


private void incr() {
value++;
if (application != null)
application.update(value);
}

public void run() {
// TODO: Complete the thread termination condition.
if (state == 2) {
holdResume();
System.out.println("state: "+state);
}
while (state==1) {
try {
Thread.sleep(100); // 1/10 second
incr();
} catch (InterruptedException e) {
// TODO: Complete the interrupt handler.
// We've been interrupted -- we terminate.
return;

}
}
// Set myThread to null so that control method can determine that
// we really have terminated.
myThread = null;
}
}

相關文章