使用synchronized块里面的run方法很奇怪

时间:2014-08-10 11:15:56

标签: java multithreading concurrency

package multithreading.concurrency.cp.bqueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class Producer implements Runnable {

    private final BlockingQueue<Object> queue;

    private int priority;

    public Producer(int priority, BlockingQueue<Object> queue) {
        this.priority = priority;
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(priority);
                synchronized (this) {
                    queue.put("object");
                    System.out.println("put  " + queue.size());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {

    private final BlockingQueue<Object> queue;

    private int priority;

    public Consumer(int priority, BlockingQueue<Object> queue) {
        this.priority = priority;
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(priority);
                synchronized (this) {
                    queue.take();
                    System.out.println("take " + queue.size());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ConsumerProducer {

    private static final int SHARED_BUFFER_CAPACITY = 10;

    public static void main(String[] args) {

        BlockingQueue<Object> sharedBuffer = new LinkedBlockingQueue<Object>(SHARED_BUFFER_CAPACITY);

        new Thread(new Producer(200, sharedBuffer)).start();
        new Thread(new Producer(300, sharedBuffer)).start();
        new Thread(new Consumer(1000, sharedBuffer)).start();
        new Thread(new Consumer(1000, sharedBuffer)).start();
    }
}

为什么我得到的输出就像运行方法中的synchronized块一样无效

take 9
put  10
take 9
take 9
put  10
put  10
take 9
put  10
take 9
put  10
take 9
take 8

1 个答案:

答案 0 :(得分:4)

为什么要对'this'进行同步?您实际上正在同步4个不同的互斥锁('this'指的是Producer或Consumer的实际实例)。 尝试使用synchronized(queue)