简体   繁体   English

如何在Android中停止线程?

[英]how to stop a thread in Android?

I'm using a Thread to initialize some resources while displaying a splash screen with a progress bar, and sometimes start a different activity (for result). 我正在使用Thread初始化一些资源,同时显示带有进度条的启动画面,有时会启动不同的活动(结果)。

At first I used AsyncTask, which works great, except that I found out that I can't use another one(Android 1.5) so I had to use a Thread. 起初我使用AsyncTask,它工作得很好,除了我发现我不能使用另一个(Android 1.5)所以我不得不使用一个Thread。

currently, my code looks like this: 目前,我的代码如下所示:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);
    m_progressBar = (ProgressBar) findViewById(R.id.progressBar);
    m_progressBar.setMax(10);
    // start the Init process
    Thread thread = new Thread(initTask);
    thread.start();

As Thread.stop() is deprecated, and I can't use Thread.interrupt(), If I press the back key, I can't stop the thread from starting a new Activity. 由于不推荐使用Thread.stop(),并且我不能使用Thread.interrupt(),如果按下后退键,我无法阻止线程启动新的Activity。

Any suggestions? 有什么建议么?

Stopping a thread requires the cooperation from the thread in question. 停止线程需要来自相关线程的合作。 The general idea is to send the thread a signal, and it regularly checks for that signal and then stops itself. 一般的想法是向线程发送信号,并定期检查该信号然后自行停止。 The simplest "signal" is a simple boolean field that it checks. 最简单的“信号”是它检查的简单布尔字段。

First, you can use multiple AsyncTasks at the same time, there is no limit on that. 首先,您可以同时使用多个AsyncTasks ,对此没有限制。 What was the problem? 出了什么问题?

Update: Indeed before 1.6 AsyncTasks were executed serially on same background thread, one after another. 更新:确实在1.6 AsyncTasks在相同的后台线程上连续执行之前。

Second, threading in java is cooperative - you can not kill a thread, but rather you have to notify it about your intent to be stopped and it then stops it itself (ie exits the run method). 其次,java中的线程是合作的 - 你不能杀死一个线程,而是你必须通知它你的意图被停止然后它自己停止(即退出run方法)。

To signal it to stop, just have a boolean field running=true which thread checks in it's main loop. 要发信号停止,只需要一个布尔字段running = true,哪个线程检查它的主循环。 When running==false thread exits the run() method. 当运行== false时,线程退出run()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM