JAVA線程鎖的問題

這幾天一直在看多線程。其中最多見的就是 生產者消費者 的問題。代碼以下:java

1. 隊列

//一個定長的隊列
Queue<Integer> queue = new LinkedList<Integer>();

2. 生產者

public void run() {
		while(true) {
                        //(1)
			synchronized(queue) {
				while(queue.size() == maxSize) {
					try {
						System.out.println("Queue is full, Producer thread waiting for, consumer to take something from queue");
						queue.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				int i = new Random().nextInt();
				queue.add(i);
				System.out.println("Producing value : " + i);
                                //(2)
				queue.notifyAll();
			}
		}
	}

3.消費者

@Override
	public void run() {
		while(true) {
			synchronized(queue) {
				while(queue.isEmpty()) {
					System.out.println("Queue is empty, Consumer thread is waiting, for producer thread to put something in queue");
					try {
						queue.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
				//消費
				System.out.println(Thread.currentThread().getName() + "value : " + queue.remove());
				queue.notifyAll();
			}
		}
	}

問題:

  1. 這個鎖是 queue拿到了,仍是 線程對象 拿到了?
  2. 當 **queue.wait()**是線程被阻塞,仍是 queue被阻塞?
  3. 假如是 queue 被阻塞,爲何還能夠 **queue.notifyAll()**還能夠執行?
  4. 假如是生產者線程對象被阻塞,消費者線程對象調用notifyAll。它怎麼知道喚醒的是生產者仍是消費者
相關文章
相關標籤/搜索