Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

android - Killing child thread from parent thread in java

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();
    }
}

Main thread has this code to start above thread:

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

My run() function is calling function like this. How to I use interrupt() in this? Please tell me any other way to kill child thread and deallocating its resources.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?

You have two choices:

  1. 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.

  2. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...