1:创建数据存储对象代码如下
public class ValueObject {
public static String value = "";
}
2:创建生产者代码如下
public class Produce {
private String lock;
public Produce(String lock) {
this.lock = lock;
}
public void setValue() {
try {
synchronized (this.lock) {
while (!ValueObject.value.equals("")) {
System.out.println("生产者" + Thread.currentThread().getName() + "WAITING 了 ☆");
this.lock.wait();
}
System.out.println("生产者" + Thread.currentThread().getName() + "RUNNABLE了");
String value = System.currentTimeMillis() + "_" + System.nanoTime();
ValueObject.value = value;
this.lock.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3:创建消费者代码如下
public class Consumer {
private String lock;
public Consumer(String lock) {
this.lock = lock;
}
public void getValue() {
try {
synchronized (this.lock) {
while (ValueObject.value.equals("")) {
System.out.println("消费者" + Thread.currentThread().getName() + "WAITING 了 △");
this.lock.wait();
}
System.out.println("消费者" + Thread.currentThread().getName() + "RUNNABLE了");
ValueObject.value = "";
this.lock.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
4:创建生产者线程代码如下
public class ThreadProduce extends Thread {
private Produce produce;
public ThreadProduce(Produce produce) {
this.produce = produce;
}
@Override
public void run() {
while (true) {
this.produce.setValue();
}
}
}
5:创建消费者线程代码如下
public class ThreadConsumer extends Thread {
private Consumer consumer;
public ThreadConsumer(Consumer consumer) {
this.consumer = consumer;
}
@Override
public void run() {
while (true) {
this.consumer.getValue();
}
}
}
6:创建测试类代码如下
public class Test {
public static void main(String[] args) throws InterruptedException {
String lock = new String();
Produce produce = new Produce(lock);
Consumer consumer = new Consumer(lock);
ThreadProduce[] threadProduce = new ThreadProduce[2];
ThreadConsumer[] threadConsumer = new ThreadConsumer[2];
for (int i = 0; i < 2; i++) {
threadProduce[i] = new ThreadProduce(produce);
threadProduce[i].setName("生产者" + (i + 1));
threadConsumer[i] = new ThreadConsumer(consumer);
threadConsumer[i].setName("消费者" + (i + 1));
threadProduce[i].start();
threadConsumer[i].start();
}
Thread.sleep(5000);
Thread[] threadArray = new Thread[Thread.currentThread().getThreadGroup().activeCount()];
Thread.currentThread().getThreadGroup().enumerate(threadArray);
for (int i = 0; i < threadArray.length; i++) {
System.out.println(threadArray[i].getName() + " " + threadArray[i].getState());
}
}
}