-----------------------------使用 synchronized  + wait + nofify ---------------------
package com.example.demo;
/**
* @author yangxj
* @date 2019-10-14 10:01
*/
public class TestMockDemo {

Object lock = new Object();

volatile boolean flag = true; // 是否需要开始生产的标记


public void product() {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
if (flag) {
System.out.println("生产: 蛋糕" + i);
flag = false;
lock.notify(); // 通知消费
}
try {
lock.wait(); // 等待消费
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public void consume(){
for (int i = 0; i < 10; i++) {
synchronized (lock) {
if (flag) {
try {
lock.wait(); // 等待生产
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费: 蛋糕" + i);
flag = true;
lock.notify(); // 通知生产
}
}
}
public static void main(String[] args) {
TestMockDemo demo = new TestMockDemo();
new Thread(demo::product).start();
new Thread(demo::consume).start();
}
}


-----------------------------------------使用 lock + await + signal ----------------------------------

package com.example.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
* @author yangxj
* @date 2019-10-14 10:01
*/
public class TestMockDemo {

ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();

volatile boolean flag = true; // 是否需要开始生产的标记


public void product() {
for (int i = 0; i < 10; i++) {
try {
lock.lock();
if (flag) {
System.out.println("生产: 蛋糕" + i);
flag = false;
condition.signal(); // 通知消费
}
try {
condition.await(); // 等待消费
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
lock.unlock();
}
}
}

public void consume() {
for (int i = 0; i < 10; i++) {
try {
lock.lock();
if (flag) {
try {
condition.await(); //等待生产
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费: 蛋糕" + i);
flag = true;
condition.signal(); // 通知生产

} finally {
lock.unlock();
}
}
}

public static void main(String[] args) {
TestMockDemo demo = new TestMockDemo();
new Thread(demo::product).start();
new Thread(demo::consume).start();
}
}

---------------------- 使用阻塞队列 BlockingQueue-----------
package com.example.demo;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

/**
* @author yangxj
* @date 2019-10-14 10:01
*/
public class TestMockDemo {

BlockingQueue queue = new SynchronousQueue<String>(); // 阻塞队列


public void product() {
for (int i = 0; i < 10; i++) {
try {
queue.put(i);
System.out.println("生产: 蛋糕" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void consume() {
for (int i = 0; i < 10; i++) {
try {
queue.take();
System.out.println("消费: 蛋糕" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
TestMockDemo demo = new TestMockDemo();
new Thread(demo::product).start();
new Thread(demo::consume).start();
}
}
posted on 2020-03-29 21:33  yang希军  阅读(294)  评论(0)    收藏  举报