[英]using synchronized block inside run method works strange
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();
}
}
为什么我无法在run方法中获得像synced block这样的输出,所以不起作用:
take 9
put 10
take 9
take 9
put 10
put 10
take 9
put 10
take 9
put 10
take 9
take 8
?
您为什么要同步“ this”? 您实际上是在4个不同的互斥对象上进行同步(“ this”是指生产者或消费者的实际实例)。 尝试使用synchronized(queue)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.