Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package lab2;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import java.util.concurrent.Semaphore;
- public class BlockingQueue<T> {
- Semaphore e = new Semaphore(1);
- Semaphore d = new Semaphore(1);
- T[] contents;
- int capacity;
- public BlockingQueue(int capacity) {
- contents = (T[]) new Object[capacity];
- this.capacity = capacity;
- }
- @Override
- public String toString() {
- return Arrays.toString(contents) ;
- }
- public void enqueue(T item) throws InterruptedException {
- e.acquire();
- T[] temp = (T[]) new Object[capacity+1];
- if (capacity >= 0) System.arraycopy(contents, 0, temp, 0, capacity);
- temp[capacity++]=item;
- this.contents = temp;
- System.out.println("e");
- e.release();
- }
- public void dequeue() throws InterruptedException {
- d.acquire();
- T [] temp = (T[]) new Object[capacity-1];
- if (capacity >= 0) System.arraycopy(contents, 0, temp, 0, capacity-1);
- this.contents= temp;
- this.capacity--;
- System.out.println("d");
- d.release();
- }
- public static void main(String[] args) throws InterruptedException {
- BlockingQueue<Integer> bq = new BlockingQueue<>(2);
- List<Thread> list = new ArrayList<>(5);
- Thread t0 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- bq.enqueue(30);
- } catch (InterruptedException ex) {
- ex.printStackTrace();
- }
- }
- });
- list.add(t0);
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- bq.enqueue(20);
- } catch (InterruptedException ex) {
- ex.printStackTrace();
- }
- }
- });
- list.add(t1);
- Thread t2 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- bq.enqueue(5);
- } catch (InterruptedException ex) {
- ex.printStackTrace();
- }
- }
- });
- list.add(t2);
- Thread t3 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- bq.dequeue();
- } catch (InterruptedException ex) {
- ex.printStackTrace();
- }
- }
- });
- list.add(t3);
- Thread t4 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- bq.dequeue();
- } catch (InterruptedException ex) {
- ex.printStackTrace();
- }
- }
- });
- list.add(t4);
- for( Thread t : list){
- t.start();
- }
- for( Thread t : list){
- t.join();
- }
- System.out.println(bq.toString());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement