هذا كود صنعته لاضع درس هنا عن كيفية استخدام wait() و notify()
لكن ليس لدي وقت حاليا لشرحه
فمن يجد بنفسه القدرة لشرحه فليتقدم
و اصلا الامر بسيط
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* @author MErsan
*/
public class ConnectionPool extends JFrame implements ActionListener {
JButton btn_Pick;
JButton btn_Restore;
JButton btn_Print;
public ConnectionPool() {
setSize(400, 400);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn_Pick = new JButton("Pick");
btn_Restore = new JButton("Restore");
btn_Print = new JButton("Print");
btn_Pick.addActionListener(this);
btn_Restore.addActionListener(this);
btn_Print.addActionListener(this);
add(btn_Pick);
add(btn_Restore);
add(btn_Print);
}
public static void main(String args[]) {
ConnectionPool form = new ConnectionPool();
form.setVisible(true);
}
private List<TestClass> objects = createObjects();
private Vector<TestClass> testVector = new Vector<TestClass>();
private List<TestClass> createObjects() {
List<TestClass> test = new ArrayList<TestClass>(5);
for (int i = 0; i < 5; i++) {
TestClass tc = new TestClass("Object " + i);
test.add(tc);
}
System.out.println("Creating Objects Done...");
return test;
}
public TestClass getObject() throws InterruptedException {
synchronized (objects) {
while (objects.isEmpty()) {
System.out.println("Waiting For Available Objects...");
objects.wait();
System.out.println("My Code Can Runnes Here...");
}
System.out.println("Object Returned...");
return objects.remove(0);
}
}
public void returnObject(TestClass test) {
synchronized (objects) {
objects.add(test);
System.out.println("Available Objects: " + objects.size());
System.out.println("Restoring Object...");
objects.notify();
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_Pick) {
btn_Pick.setEnabled(false);
new Thread(new Runnable() {
public void run() {
try {
while (true) {
testVector.add(getObject());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
} else if (e.getSource() == btn_Restore) {
returnObject(testVector.elementAt(0));
testVector.remove(0);
} else if (e.getSource() == btn_Print) {
System.out.println("Available Objects: " + objects.size());
}
}
}public class TestClass {
private String name;
public TestClass(String name) {
this.name = name;
}
}


