本文介绍了通过按钮控制线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要一张code来控制一个线程。例如,使用三个按钮:启动,停止和暂停,preSS其中之一,并对其执行的操作。像preSS上启动,然后启动线程,preSS停止实际上停止线程,并暂停分别执行暂停操作。

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.

推荐答案

启动一个线程是简单Thread.start()。停止一个线程可以像设置,在run方法异步地检查一个标志一样简单,但可能需要包括调用了Thread.interrupt()。暂停线程是比较麻烦的,但也可以使用cauases run方法产生的过程,而不是一个标志位来完成。下面是一些(未经测试)code:

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.

这篇关于通过按钮控制线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:47