java线程无法退出程序_java的线程问题。难!

程序的执行环境:windows2000,jdk1.3.

问题:我有两个类,一个是主程序类,一个是线程类。在主程序里启动一定

数目的线程。我怎么才能在主程序中知道所有线程都已执行完毕,而

后主程序再结束。

我已经用过在主程序里用循环的方法判断每一个线程是否死掉,但这样做效

率太低。有没有更好的方法,或不用循环判断的方法。

|

好像jdk里有个这样的例子吧?去找找看。

具体实现方法记得是:子线程类有个静态变量,每创建一个子线程就把该变量加1;

每个子线程退出时把该变量减1;当该变量减到0时,通知主线程,然后主线程退出。

|

try something like this:

1. keep a thread count, when you create a new thread, increment the count (needs synchronized)

2. pass into the new thread an instance of an interface the main thread implements

3. When the new thread ends, it will call some function in that inteface. In this function, the thread count (needs synchronized) will be decremented. When the count becomes 0, it will notify the main thread, then you can terminate the main thread

|

首先,你的main  thread在产生完所有的其他线程之后,要记住

产生了几个(有没有超生游击队),并且不能退出去,而要等在那儿,你可

可以用Object.wait()

每个工作线程在结束之前,要通知主线程,可以用

Object.notify()/Object.notifyAll()

主线程被唤醒后,要计算/判断当前活着的工作线程数,若为0则

退出,否则继续Object.wait()

以上未考虑notify失效等问题,不是很实用,每个工作线程在退出

前,可和主线程多次通信,确保counter被剪过再退出:要不然不是

白牺牲了吗?哈哈哈哈哈

|

是有while,但不是死循环,没有影响效率:

class mainThread{

static byte[] counterLocker = new byte[0];  //a locker

static int counter;

mainDo(){

//make new Thread;

counter++;

while (counter>0) {

synchronized(counterLocker){

counterLocker.wait();

counter--;

}

}

}

}

working Thread 大概是这样的:

public void run(){

//...

mainThread.counterLocker.notify();}

}

大概是这样的。。。

|

我的程序中有这样的方法:

每创建一个新的线程时,把自己加入一个vector中,退出时就把自己从vector中移出。

因为我的程序没有必要在vector为空时退出,不过我想你可以开出一个新的线程来监视vector是否为空,不用循环,因为是vector,对吧,其实与你的想法差不多。

在我的程序中只是要主线程结束时,让每个线程都能释放所点用的资源。

|

你把所有的线程都放入一个线程组,用activeCount()函数来判断此线程组中还有没有线程运行,入返回为0就说明运行完毕。(我的一点建议,希望对你有一点帮助)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值