生产一个消费一个
import java.util.concurrent.locks.*;
class ProducerConsumer {
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void produce() throws Exception {
lock.lock();
try {
while (number != 0) {
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName() + "+1");
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void consume() throws Exception {
lock.lock();
try {
while (number == 0) {
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName() + "-1");
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
for (int i = 0; i < 10; i++) {
new Thread(()->{
try {
pc.produce();
} catch (Exception e) {
e.printStackTrace();
}
}, "producer").start();
}
for (int i = 0; i < 10; i++) {
new Thread(()->{
try {
pc.consume();
} catch (Exception e) {
e.printStackTrace();
}
}, "consumer").start();
}
}
}

buffersize
import java.util.concurrent.locks.*;
class ProducerConsumer2 {
private int number = 0;
private int size = 3;
private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
public void produce() throws Exception {
lock.lock();
try {
while (number == size) {
notFull.await();
}
number++;
System.out.println(Thread.currentThread().getName() + "+1" + " curNum: " + number);
notEmpty.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void consume() throws Exception {
lock.lock();
try {
while (number == 0) {
notEmpty.await();
}
number--;
System.out.println(Thread.currentThread().getName() + "-1" + " curNum: " + number);
notFull.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ProducerConsumer2 pc = new ProducerConsumer2();
for (int i = 0; i < 10; i++) {
new Thread(()->{
try {
pc.produce();
} catch (Exception e) {
e.printStackTrace();
}
}, "producer").start();
}
for (int i = 0; i < 10; i++) {
new Thread(()->{
try {
pc.consume();
} catch (Exception e) {
e.printStackTrace();
}
}, "consumer").start();
}
}
}
