管程法
public class SczAndXfz {
public static void main(String[] args) {
Container container = new Container();
new Producer(container).start();
new Consumer(container).start();
}
}
class Producer extends Thread{
Container container;
public Producer(Container container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
container.push(new Product(i));
System.out.println("生产者生产第"+i+"个产品");
}
}
}
class Consumer extends Thread{
Container container;
public Consumer(Container container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
Product pop = container.pop();
Integer id = pop.id;
System.out.println("消费者消费第"+id+"个产品");
}
}
}
class Container{
/**
* 容器
*/
Product[] products = new Product[10];
/**
*计数器
*/
int count = 0;
public synchronized void push(Product product){
//容器满了该方法等待
if (count==products.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
products[count] = product;
count++;
//有货通知消费者消费
this.notifyAll();
}
public synchronized Product pop(){
//没有货消费者等待
if (count == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Product pro = products[count];
this.notifyAll();
return pro;
}
}
class Product{
Integer id;
public Product(Integer id) {
this.id = id;
}
}
信号灯
public class TestPC {
public static void main(String[] args) {
Shop shop = new Shop();
ExecutorService executorService=new ThreadPoolExecutor(2,5,
1L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
executorService.execute(new MeiZu(shop));
executorService.execute(new Shopper(shop));
executorService.shutdown();
}
}
class MeiZu extends Thread{
Shop shop;
public MeiZu(Shop shop) {
this.shop = shop;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2==0){
shop.produce(new Phone("魅族17Pro天青色"));
}else{
shop.produce(new Phone("魅族17Pro纯白色"));
}
}
}
}
class Shopper extends Thread{
Shop shop;
public Shopper(Shop shop) {
this.shop = shop;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
shop.consumer();
}
}
}
class Phone{
String name;
public Phone(String name) {
this.name = name;
}
}
class Shop{
/**
* 厂商生产,消费者等待 true
* 消费者消费,厂商等待flase
*/
Phone phone;
boolean flag = true;
public synchronized void produce(Phone phone){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("厂商生产了"+phone.name);
this.phone = phone;
this.flag = !this.flag;
//通知消费者消费
this.notifyAll();
}
public synchronized void consumer(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费者购买了"+phone.name);
this.flag = !this.flag;
//通知生产者生产
this.notifyAll();
}
}