Skip to content

Instantly share code, notes, and snippets.

@huantt
Created June 7, 2016 16:28
Show Gist options
  • Save huantt/4f23eb25f6c2a4e09bab5277d30c6b7d to your computer and use it in GitHub Desktop.
Save huantt/4f23eb25f6c2a4e09bab5277d30c6b7d to your computer and use it in GitHub Desktop.
Tu tao Queue chuc nang giong voi ArrayBlockingQueue
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MyQueue;
import java.util.LinkedList;
import java.util.Queue;
/**
*
* @author Huan
*/
public class MyQueue<T> {
private Queue<T> myQueue = new LinkedList<>();
private int size;
Object object = new Object();
public MyQueue(int size) {
this.size = size;
}
public void put(T string) throws InterruptedException {
synchronized (object) {
while (myQueue.size() == size) {
object.wait();
}
myQueue.add(string);
System.out.println("putted" + string);
object.notifyAll(); // Phai notifyAll de tranh cac Thread su dung queue bi missing
}
}
public T take() throws InterruptedException {
synchronized (object) {
while (myQueue.isEmpty()) {
object.wait();
}
T str = myQueue.poll();
object.notifyAll();
return str;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment