3

我在java android平台上工作。我正在从主线程创建一个子线程。我想根据我的要求停止子线程。我的子线程具有简单的功能,没有任何循环。我想随时杀死子线程并释放它正在使用的资源。我搜索了它,发现了 inturrupt() 函数。我的主题是:

public class childThread implements Runnable{
  public void run() {
     firstFunction();
     secondFunction();
    }
}

主线程有以下代码在线程之上启动:

Thread tChild;
tChild = new Thread(new childThread(), "Child Thread");
tChild.start();

我的run()函数是这样调用函数。我如何interrupt()在这个中使用?请告诉我任何其他方式来杀死子线程并释放其资源。

4

5 回答 5

5

通过线程的合作,您可以使用它支持的任何方法停止该线程。没有线程的合作,就没有理智的方法可以阻止它。例如,考虑线程是否持有锁并将共享资源置于无效状态。如果没有它的合作,你怎么能阻止那个线程呢?

你有两个选择:

  1. 对你的线程进行编码,这样它们就不会做你不希望它们做的工作。对它们进行编码,以便它们在无工作可做时终止自己。这样,他们就不需要其他线程从外部“进入”。

  2. 对您的线程进行编码,以便它们提供某种方式被告知它们应该终止,然后它们干净地终止。

但这些是你的选择——它不能靠魔法起作用。

想象一个线程在工作,就像你姐姐借你的车一样。如果你需要车回来,你需要你姐姐的合作才能把它拿回来。您可以安排让她在您需要汽车时自己回来,或者您可以安排让您在需要汽车时告诉她然后她回来。但是你不能改变这样一个事实,她必须知道如何把车开回来,否则它就回不来了。

线程操纵进程资源并将它们置于无效状态。他们必须在终止之前修复事物,否则进程上下文将损坏。

于 2013-06-15T12:27:59.600 回答
2

因为你没有任何循环,检查 Thread.interrupted() 值,我假设你的 firstFunction(); secondFunction();,做繁重的工作,你将不得不检查函数 firstFunction(); 中的适当点。第二函数();条件 Thread.interrupted(),如果为真则结束该方法。我知道你没有循环,但从概念上讲是这样的,

    Runnable runnable = new Runnable() {
      private int counter;

      public void run() {
        while(true){
          System.out.println(">> Executing " + counter++);

          if(Thread.interrupted()){
            break;
          }
        }

      }
    };

    Thread thread = new Thread(runnable);
    thread.start();

    Thread.sleep(10 * 1000);

    thread.interrupt();
于 2013-06-15T12:05:48.563 回答
0

您的子线程需要Thread.interrupted()定期检查并在返回 true 时退出。

你的代码是否有循环并不重要。您只需要在代码执行路径中选择各个点即可查看是否需要取消。

于 2013-06-15T11:47:00.593 回答
0

只需在 tChild 对象上调用中断,它就会中断您的子线程

Thread tChild;
tChild = new Thread(new childThread(), "Child Thread");
tChild.start();
//...
tChild.interrupt();
于 2013-06-15T11:56:09.603 回答
-1

用 try catch 包围你的代码。捕获 InterruptedException 然后出来。如果有循环,请将catch 语句放在循环之外/如果catch 在内部则中断循环。

    Runnable runnable = new Runnable() {  
      public void run() {  
          try {  
               while(true) {  
                    // your code  
               }                   
           }(InterruptedException e) {  
                // It comes out   
           }
}
于 2015-02-04T13:26:31.240 回答