基于Synchronized實現(xiàn)
package com.wan.situ;
import java.util.ArrayList;
public class ThreadTest {
public int maxSize;
public final ArrayList<String> products = new ArrayList<>();
public Worker worker;
public Consumer consumer;
public boolean isRun = false;
private static int index;
public synchronized String getNewIndex() {
return (index++) + "";
}
public ThreadTest(int size) {
this.maxSize = size;
this.worker = new Worker();
this.consumer = new Consumer();
}
public void start() {
this.isRun = true;
this.consumer.start();
this.worker.start();
}
class Worker extends Thread {
@Override
public void run() {
while (isRun) {
synchronized (products) {
if (products.size() < maxSize) {
try {
Thread.sleep(1000);
String p = getNewIndex();
products.add(p);
System.out.println("生產(chǎn)者 + " + p);
products.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
System.out.println("生產(chǎn)者 - wait");
products.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Consumer extends Thread {
@Override
public void run() {
while (isRun) {
synchronized (products) {
if (products.size() > 0) {
try {
Thread.sleep(1000);
System.out.println("消費者 - " + products.remove(0));
products.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
System.out.println("消費者 - wait");
products.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
new ThreadTest(10).start();
}
}
消費者 - wait
生產(chǎn)者 + 0
生產(chǎn)者 + 1
生產(chǎn)者 + 2
生產(chǎn)者 + 3
生產(chǎn)者 + 4
生產(chǎn)者 + 5
生產(chǎn)者 + 6
生產(chǎn)者 + 7
生產(chǎn)者 + 8
生產(chǎn)者 + 9
生產(chǎn)者 - wait
消費者 - 0
消費者 - 1
消費者 - 2
消費者 - 3
消費者 - 4
消費者 - 5
消費者 - 6
消費者 - 7