各位大大:
程序中的工作,通过循环来做的话,太费时间,所以决定用线程来实现,大概上百个.
但是我不想100个线程同时进行, 希望让他们5个5个的运行,其他的都wait(), 一个运行完毕后唤醒等待队列中的下一个。不知道该如何控制,请指教,最好给出简单的代码
程序中的工作,通过循环来做的话,太费时间,所以决定用线程来实现,大概上百个.
但是我不想100个线程同时进行, 希望让他们5个5个的运行,其他的都wait(), 一个运行完毕后唤醒等待队列中的下一个。不知道该如何控制,请指教,最好给出简单的代码
请继续指教
{
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();
}
}执行通过.