- 论坛徽章:
- 0
|
if your programe execute a high-cost-operation under multi-thread
and want to assign the number that the high-cost-operation can be invoked at the same time...
actually "Thread.sleep()" can't do this, because that your programe is running under multi-thread environment
so check the following simple code, hope it is helpful 
- public class ConcurrentControler {
-
- private int limit;
- private int size = 0;
- private Object lock = new Object();
-
-
- public ConcurrentControler(){}
-
-
- public int getLimit() {
- return limit;
- }
- public void setLimit(int limit) {
- this.limit = limit;
- }
- public void request() throws InterruptedException
- {
- synchronized(lock)
- {
- while (size>=limit)
- lock.wait();
- ++size;
- }
-
- }
- public void finish()
- {
- synchronized(lock)
- {
- --size;
- lock.notifyAll();
- }
- }
-
- public static void main(String[] args) {
-
- ConcurrentControler controler = new ConcurrentControler();
- controler.setLimit(3);
- new Thread( new SimpleTest(controler) ).start();
- new Thread( new SimpleTest(controler) ).start();
- new Thread( new SimpleTest(controler) ).start();
- new Thread( new SimpleTest(controler) ).start();
- new Thread( new SimpleTest(controler) ).start();
- new Thread( new SimpleTest(controler) ).start();
- new Thread( new SimpleTest(controler) ).start();
- new Thread( new SimpleTest(controler) ).start();
- new Thread( new SimpleTest(controler) ).start();
-
- }
-
- public static class SimpleTest implements Runnable
- {
- private ConcurrentControler queue;
- public SimpleTest(ConcurrentControler obj)
- {
- this.queue = obj;
- }
-
- public void run() {
-
- try{
- queue.request();
- }catch(Exception ignored){ignored.printStackTrace();}
-
- System.out.println("execute...");
- //execute some kind of heavy method here
- try{
- //Thread.sleep(3000);
- }catch(Exception ignored){ignored.printStackTrace();}
- queue.finish();
-
- }
-
- }
- }
复制代码
[ 本帖最后由 iamyess 于 2008-11-29 08:19 编辑 ] |
|