请教一个线程控制的问题.

jassonlu 2005-11-28 04:43:56
各位大大:
程序中的工作,通过循环来做的话,太费时间,所以决定用线程来实现,大概上百个.
但是我不想100个线程同时进行, 希望让他们5个5个的运行,其他的都wait(), 一个运行完毕后唤醒等待队列中的下一个。不知道该如何控制,请指教,最好给出简单的代码
...全文
126 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
jassonlu 2005-11-29
  • 打赏
  • 举报
回复
结算
jassonlu 2005-11-29
  • 打赏
  • 举报
回复
已经解决, 一开始5个运行,其他全部wait(),一个运行完毕后在RUN()的最后唤醒wait队列中的一个进入运行,现在看来系统吃得消, 而且等待队列中有多少个对系统有影响吗? 只要同时运行的不超过5个,我看就没问题.

散分~~~
yuzl32 2005-11-28
  • 打赏
  • 举报
回复
系统资源受不了.
suprwx 2005-11-28
  • 打赏
  • 举报
回复
我觉得同时生成100个线程是不可取的,gemouzhi(gemouzhi)说的有道理
liu_you 2005-11-28
  • 打赏
  • 举报
回复
import java.util.Date;

public class Manager
{
int free=5;
public synchronized AbThread createThread()
{
if(free>0)
{
use();
return new AbThread(this);
}
else
{
_wait();
return null;
}
}
public synchronized void use(){free--;}
public synchronized void free(){free++;}
public void _wait()
{
synchronized(this)
{
try
{
wait();
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
public void _notify()
{
synchronized(this)
{
notify();
}
}
public static void main(String[] args)
{
Manager man=new Manager();
for(int i=0;i<100;)
{
AbThread t=man.createThread();
if(t!=null){t.start();i++;}
}
}
}
class AbThread extends Thread
{
AbThread(Manager man){this.man=man;}
Manager man;
public void run()
{
System.out.print(this);
System.out.println(""+new Date());
try
{
Thread.sleep(1000);
}catch(InterruptedException ex)
{
ex.printStackTrace();
}
man.free();
man._notify();
}
}

执行通过.
gemouzhi 2005-11-28
  • 打赏
  • 举报
回复
就在run方法结束的时候通知啊。进程是主动方

或者你可以继续使用这个线程。
jassonlu 2005-11-28
  • 打赏
  • 举报
回复
但是如何知道 之前创建的那些进程哪几个运行完毕了呢?
gemouzhi 2005-11-28
  • 打赏
  • 举报
回复
我的意思是5个中其中只要有运行完的,就通知创建新线程,全创建起来不好。
jassonlu 2005-11-28
  • 打赏
  • 举报
回复
5个5个的运行的话,有的先完成,有的后完成,浪费时间啊!

我想用 wait() notifyAll()来控制他们,但是不会做 :(
请继续指教
gemouzhi 2005-11-28
  • 打赏
  • 举报
回复
那你还不如5个5个的运行,何必wait

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧