synchronized实现
public class Costumer implements Runnable {
@Override
public void run() {
while (true) {
synchronized (Goods.LOCK) {
if(Goods.COUNT == 0) {
System.out.println("生产者生产商品");
Goods.COUNT = 1;
Goods.LOCK.notifyAll();
} else {
try {
Goods.LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Producter implements Runnable {
@Override
public void run() {
while (true) {
synchronized (Goods.LOCK) {
if (Goods.COUNT == 1) {
System.out.println("消费者消费商品");
Goods.COUNT = 0;
Goods.LOCK.notifyAll();
} else {
try {
Goods.LOCK.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Goods {
public static volatile int COUNT = 1;
public static Object LOCK = new Object();
public static void main(String[] args) {
new Thread(new Costumer()).start();
new Thread(new Producter()).start();
}
}
ReentrantLock实现
public class Producter implements Runnable {
@Override
public void run() {
while (true) {
Goods.LOCK.lock();
try {
if (Goods.COUNT == 1) {
System.out.println("消费者消费商品");
Goods.COUNT = 0;
Goods.CONDITION.signalAll();
} else {
try {
Goods.CONDITION.await();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
Goods.LOCK.unlock();
}
}
}
}
public class Costumer implements Runnable {
@Override
public void run() {
while (true) {
Goods.LOCK.lock();
try {
if(Goods.COUNT == 0) {
System.out.println("生产者生产商品");
Goods.COUNT = 1;
Goods.CONDITION.signalAll();
} else {
try {
Goods.CONDITION.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
Goods.LOCK.unlock();
}
}
}
}
public class Goods {
public static volatile int COUNT = 1;
public static ReentrantLock LOCK = new ReentrantLock();
public static Condition CONDITION = LOCK.newCondition();
}