BlockingQueue
public class BlockingQueue{
private Queuequeue = new LinkedList ();
String testingwait = new String();
private int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
public synchronized void put(T element) throws InterruptedException {
while(queue.size() == capacity) {
wait();
}
queue.add(element);
notifyAll();
}
public synchronized T take() throws InterruptedException {
while(queue.isEmpty()) {
wait();
}
T item = queue.remove();
notify();
return item;
}
}
MyThread
public class MyThread extends Thread {
BlockingQueuequeue = null;
String threadname = null;
public MyThread(String threadname,BlockingQueuequeue) {
super(threadname);
// TODO Auto-generated constructor stub
this.queue = queue;
this.threadname = threadname;
}
public void run() {
if(threadname.equals("PUTTINGTHREAD")){
for (int i = 0; i < 10; i++) {
try {
queue.put("value"+i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
for (int i = 0; i < 10; i++) {
try {
queue.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
The Executable Class
public class TestThread {
public static void main(String[] args) {
BlockingQueuequeue = new BlockingQueue (5);
Thread t = new MyThread("PUTTINGTHREAD",queue);
Thread t1 = new MyThread("TAKINGTHREAD",queue);
t.start();
t1.start();
}
}
No comments:
Post a Comment