java的线程问题。难!
程序的执行环境:windows2000,jdk1.3.
问题:我有两个类,一个是主程序类,一个是线程类。在主程序里启动一定
数目的线程。我怎么才能在主程序中知道所有线程都已执行完毕,而
后主程序再结束。
我已经用过在主程序里用循环的方法判断每一个线程是否死掉,但这样做效
率太低。有没有更好的方法,或不用循环判断的方法。
问题点数:98、回复次数:16Top
1 楼karma(无为MS MVP)回复于 2001-09-29 04:05:34 得分 10
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 threadTop
2 楼hahaha88(忧郁的眼神,稀嘘的胡子喳)回复于 2001-09-29 04:41:11 得分 10
首先,你的main thread在产生完所有的其他线程之后,要记住
产生了几个(有没有超生游击队),并且不能退出去,而要等在那儿,你可
可以用Object.wait()
每个工作线程在结束之前,要通知主线程,可以用
Object.notify()/Object.notifyAll()
主线程被唤醒后,要计算/判断当前活着的工作线程数,若为0则
退出,否则继续Object.wait()
以上未考虑notify失效等问题,不是很实用,每个工作线程在退出
前,可和主线程多次通信,确保counter被剪过再退出:要不然不是
白牺牲了吗?哈哈哈哈哈
Top
3 楼flytsu(卡休)回复于 2001-09-29 05:16:43 得分 0
非常感谢二位的回答。但是还是要在主程序里循环的判断才能解决。
如果在主程序里循环作判断,会使程序的执行效率很低!
Top
4 楼hahaha88(忧郁的眼神,稀嘘的胡子喳)回复于 2001-09-29 06:00:52 得分 10
是有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();}
}
大概是这样的。。。Top
5 楼karma(无为MS MVP)回复于 2001-09-29 06:50:21 得分 0
If you use my callaback method, there is no wait at all.Top
6 楼karma(无为MS MVP)回复于 2001-09-29 06:51:24 得分 0
callback, not callaback, typoTop
7 楼karma(无为MS MVP)回复于 2001-09-29 06:54:18 得分 0
Sorry, I assumed your main thread is a GUI thread, if not, then you have to wait.Top
8 楼flytsu(卡休)回复于 2001-09-29 07:15:20 得分 0
主程序没有GUI界面!Top
9 楼hexiaofeng(java爱好者)回复于 2001-09-29 08:04:11 得分 0
?Top
10 楼flytsu(卡休)回复于 2001-09-29 08:09:50 得分 0
服务线程的生命周期是怎么样的呢?Top
11 楼hyhong_h(黄黄)回复于 2001-09-29 08:36:57 得分 48
好像jdk里有个这样的例子吧?去找找看。
具体实现方法记得是:子线程类有个静态变量,每创建一个子线程就把该变量加1;
每个子线程退出时把该变量减1;当该变量减到0时,通知主线程,然后主线程退出。Top
12 楼sharetop(九尾灵狐)回复于 2001-09-29 09:18:35 得分 10
我的程序中有这样的方法:
每创建一个新的线程时,把自己加入一个vector中,退出时就把自己从vector中移出。
因为我的程序没有必要在vector为空时退出,不过我想你可以开出一个新的线程来监视vector是否为空,不用循环,因为是vector,对吧,其实与你的想法差不多。
在我的程序中只是要主线程结束时,让每个线程都能释放所点用的资源。
Top
13 楼sharetop(九尾灵狐)回复于 2001-09-29 09:19:18 得分 0
不知道是否对你有帮助?一点想法而已。
Top
14 楼gxj0637(╭∩╮(︶︿︶)╭∩╮)回复于 2001-09-29 09:44:50 得分 10
你把所有的线程都放入一个线程组,用activeCount()函数来判断此线程组中还有没有线程运行,入返回为0就说明运行完毕。(我的一点建议,希望对你有一点帮助)Top
15 楼flytsu(卡休)回复于 2001-09-29 12:36:49 得分 0
放到线程组中,也是要循环检测!Top
16 楼flytsu(卡休)回复于 2001-09-29 12:40:52 得分 0
程序是这样的:主程序开一些线程,每次开的线程数不一样,主程序要记录最后的结束的线程的结束时间!Top




