共享队列ShareQueue

来源:互联网 发布:外星人windows hello 编辑:程序博客网 时间:2024/06/11 06:42
public class SharedQueue {class Node {Object task;Node next;Node(Object task) {this.task = task;next = null;}}private Node head = new Node(null);private Node last = head;private volatile int w;private Object putLock = new Object();private Object takeLock = new Object();public void put(Object task) {System.out.println("...... " + Thread.currentThread().getName() + " wants to get the  putLock....");synchronized (putLock) {System.out.println("...... " + Thread.currentThread().getName() + " gets putLock....");Node p = new Node(task);last.next = p;last = p;System.out.println("...... putting "+ task);if (w > 0) {System.out.println("...... w = " + w);putLock.notify();}}}public Object take() {Object task = null;System.out.println(Thread.currentThread().getName() + " wants to get the  takeLock....");synchronized (takeLock) {System.out.println(Thread.currentThread().getName() + " gets takeLock....");while (isEmpty()) {try {System.out.println(Thread.currentThread().getName() + " want to get putLock....");synchronized (putLock) {System.out.println(Thread.currentThread().getName() + " gets putLock....");w++;putLock.wait();w--;}} catch (Exception e) {// TODO: handle exception}}{Node first = head.next;task = first.task;first.task = null;head = first;}}System.out.println(Thread.currentThread().getName() + " releases takeLock....");return task;}private boolean isEmpty() {return head.next == null;}public static void main(String[] args) {final SharedQueue queue = new SharedQueue();new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 1000; i++) {queue.put(Integer.valueOf(i));try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 1000; i++) {try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("============taking " + queue.take());}}}).start();new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 1000; i++) {try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("----------------taking " + queue.take());}}}).start();}}

0 0