[we create a thread Pool which types users use same resourses][1] import java.util.Vector; class Model extends Thread { @Override public void run() { while(true) { synchronized (this) { try { wait(); } catch (InterruptedException e) { } } for (int i = 0; i <= 10; i++) { Thread t1 = Thread.currentThread(); System.out.println(t1.getName() + : + i); Util.sleep(100); } synchronized (this) { notify(); } } } } class ThreadPoolManager { @SuppressWarnings(rawtypes) private Vector pool = new Vector(); @SuppressWarnings(unchecked) public void init() { Model model; for (int i = 0; i < 10; i++) { model = new Model(); model.start(); pool.add(model); } } public Model checkOut() { Model model; if (pool.size() > 0) { model = (Model) pool.remove(0); } else { model = new Model(); model.start(); } return model; } @SuppressWarnings({ unchecked, deprecation }) public void checkIn(Model model) { if (pool.size() < 10) { pool.add(model); } else { model.stop(); } } @SuppressWarnings(deprecation) public void release() { Model model; for (int i = 0; i < pool.size();) { model = (Model) pool.remove(0); model.stop(); } } } class User1 extends Thread { ThreadPoolManager pm; User1(ThreadPoolManager pm) { this.pm = pm; } @Override public void run() { while(true) { Model model = pm.checkOut(); synchronized (model) { model.notify(); } synchronized (model) { try { model.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } pm.checkIn(model); Util.sleep(2000); } } } } class User2 extends Thread { ThreadPoolManager pm; User2(ThreadPoolManager pm) { this.pm = pm; } @Override public void run() { while(true) { Model model = pm.checkOut(); synchronized (model) { model.notify(); } synchronized (model) { try { model.wait(); } catch (InterruptedException e) { e.printStackTrace(); } pm.checkIn(model); Util.sleep(2000); } } } } class User3 extends Thread { ThreadPoolManager pm; User3(ThreadPoolManager pm) { this.pm = pm; } @Override public void run() { while(true) { Model model = pm.checkOut(); synchronized (model) { model.notify(); } synchronized (model) { try { model.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } pm.checkIn(model); Util.sleep(2000); } } } }
©