问题描述
我在Java android平台的工作。我创建从主线程子线程。我想停止子线程作为我的质量要求。我的孩子线程不具有任何环路简单的功能。我想杀死子线程和免费资源被使用,每当我想要的。我搜索了它,我发现inturrupt()function.my线程是:
I am working in java android platform. I am creating a child thread from main thread. I want to stop child thread as my requirments. My child thread has simple function which doesn't have any loop. I want to kill child thread and free resources it is using, whenever I want. I searched for it and I found inturrupt() function.my thread is:
public class childThread implements Runnable{
public void run() {
firstFunction();
secondFunction();
}
}
主线程有这个code开始上述主题:
Main thread has this code to start above thread:
Thread tChild;
tChild = new Thread(new childThread(), "Child Thread");
tChild.start();
我的run()函数调用被这样的功能。如何我使用本inturrupt()?请告诉我任何其他方式杀死子线程和释放资源。谢谢你。
my run() function is calling function like this. How to I use inturrupt() in this? Please tell me any other way to kill child thread and deallocating its resources. Thank you.
推荐答案
通过线程的合作,您可以使用它支持任何方法可以停止线程。如果没有一个线程的合作,没有理智的方法来阻止它。考虑,例如,如果该线程持有的锁,并把共享资源成无效状态。你怎么能阻止该线程没有它的合作?
With a thread's cooperation, you can stop that thread using any method it supports. Without a thread's cooperation, there is no sane way to stop it. Consider, for example, if the thread holds a lock and has put a shared resource into an invalid state. How can you stop that thread without its cooperation?
您有两种选择:
-
code你的线程,使他们不这样做,你不希望他们做的工作。 code他们,让他们自己结束时,他们没有工作可做。这样,他们就不会需要一些其他的线程从外到达到。
Code your threads so that they don't do work that you don't want them to do. Code them so they terminate themselves when they have no work to do. That way, they won't need some other thread to "reach in" from the outside.
code你的线程,让他们提供一些方法被告知,他们应该终止,然后他们终止干净。
Code your threads so that they provide some way to be told that they should terminate and then they terminate cleanly.
但这些都是你的选择 - 它不能用魔法工作
But those are your choices -- it can't work by magic.
想想一个线程做的工作就像你妹妹借你的车。如果你需要的车回来,你需要在你姐姐的合作把它找回来。您可以安排是为了让她回来,当你需要的车由她自己,或者你可以安排是为了让你告诉她,当你需要的车,然后她回来。但是你不能改变她必须知道如何把车开回来,否则将无法收回的事实。
Think of a thread doing work like your sister borrowing your car. If you need the car back, you need your sister's cooperation to get it back. You can either arrange is so that she comes back when you need the car by herself or you can arrange is so that you tell her when you need the car and then she comes back. But you can't change the fact that she has to know how to bring the car back or it won't get back.
线程操作过程中的资源,并把它们变成无效状态。他们拥有终止或进程上下文会被破坏之前修复的东西。
Threads manipulate process resources and put them into invalid states. They have to repair things before they terminate or the process context will become corrupt.
这篇关于从父线程Java中杀子线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!