java 中杀死子线程,从父线程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 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?

You have two choices:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值