单击按钮时线程启动,并通过另一个按钮单击结束线程

时间:2016-04-28 08:55:24

标签: java android thread-safety

Sir请帮我添加一个按钮点击开始的线程,然后点击另一个按钮结束线程。在这之间,我有一个声音播放,直到线程停止。

3 个答案:

答案 0 :(得分:2)

您可以尝试这个简单的代码:

    final volatile boolean toExit = false;
    final Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            while(!toExit){
                // Your code
                Thread.sleep(100);
            }
        }
    });

    findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            t.start();
        }
    });

    findViewById(R.id.button2).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            toExit = true;
        }
    });

点击button2后线程将停止并运行到while(!toExit)

答案 1 :(得分:0)

不推荐使用Threads stop方法。 最好的解决方案是在run方法中使用布尔变量。

你的主题:

var Font = UIFont.SystemFontOfSize(16);
var textLayer = new CATextLayer();
textLayer.ForegroundColor = UIColor.Red.CGColor; // TextColor.CGColor;
textLayer.SetFont(CGFont.CreateWithFontName(Font.FontDescriptor.Name));

在您的活动中:

public class MyThread implements Runnable {

private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private volatile boolean running = true;

public void terminate() {
    running = false;
}

@Override
public void run() {
    while (running) {
        try {
            //Your code that needs to be run multiple times

            LOGGER.debug("Processing");
        } catch (InterruptedException e) {
            LOGGER.error("Exception", e);
            running = false;
        }
    }

}
}

答案 2 :(得分:0)

  

使用以下代码

public class SomeBackgroundProcess implements Runnable {

Thread backgroundThread;

public void start() {
   if( backgroundThread == null ) {
      backgroundThread = new Thread( this );
      backgroundThread.start();
   }
}

public void stop() {
   if( backgroundThread != null ) {
      backgroundThread.interrupt();
   }
}

public void run() {
    try {
       Log.i("Thread starting.");
       while( !backgroundThread.interrupted() ) {
          doSomething();
       }
       Log.i("Thread stopping.");
    } catch( InterruptedException ex ) {
       // important you respond to the InterruptedException and stop processing 
       // when its thrown!  Notice this is outside the while loop.
       Log.i("Thread shutting down as it was requested to stop.");
    } finally {
       backgroundThread = null;
    }
}

希望这会对你有所帮助