Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

java - Control thread through button

We require a piece of code to control a thread. For example, use three buttons like start, stop and pause, press one of them and perform the action against it. Like press start then start the thread, press stop actually stops thread and pause perform pause action respectively.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Starting a thread is simple with Thread.start(). Stopping a thread can be as simple as setting a flag that is checked asychronously in the run method, but may need to include a call to Thread.interrupt(). Pausing a thread is more problematic, but could also be done using a flag that cauases the run method to yield instead of process. Here is some (untested) code:

class MyThread extends Thread {
   private final static int STATE_RUN = 0, STATE_PAUSE = 2, STATE_STOP = 3;
   private int _state;

   MyThread() {
      _state = STATE_RUN;
   }

   public void run() {
       int stateTemp;

       synchronized(this) {
           stateTemp = _state;
       }

       while (stateTemp != STATE_STOP) {
           switch (stateTemp) {
               case STATE_RUN:
                   // perform processing
                   break;
               case STATE_PAUSE:
                   yield();
                   break;
           }
           synchronized(this) {
               stateTemp = _state;
           }
       }
       // cleanup
   }

   public synchronized void stop() {
        _state = STATE_STOP;
        // may need to call interrupt() if the processing calls blocking methods.
   }

   public synchronized void pause() {
        _state = STATE_PAUSE;
        // may need to call interrupt() if the processing calls blocking methods.
        // perhaps set priority very low with setPriority(MIN_PRIORITY);
   }

   public synchronized void unpause() {
        _state = STATE_RUN;
        // perhaps restore priority with setPriority(somePriority);
        // may need to re-establish any blocked calls interrupted by pause()
   }
}

As you can see it can quite quickly get complex depending on what you are doing in the thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...