也是涉及到多线程的
以下是生产者消费者网上示例
https://blog.csdn.net/antony9118/article/details/51481884
为什么 java wait/notify 必须与 synchronized 一起使用,jvm究竟做了些什么
/**
* @author jy
* @date 2018年5月15日
* <p>Description: </p>
*/
package com.threadtest;
import java.util.Queue;
/**
* @author jy
*
*/
public class Producer implements Runnable{
final Queue queue;
public Producer(Queue queue) {
super();
this.queue = queue;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
synchronized(queue){
for(int i=0;i<4;i++){
if(queue.size()>=1){
try {
queue.wait();
System.out.println("queue is full");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
queue.add(i);
System.out.println("produce"+i);
queue.notify();
}
}
}
}
}
/**
* @author jy
* @date 2018年5月15日
* <p>Description: </p>
*/
package com.threadtest;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author jy
*
*/
public class Consumer implements Runnable {
final Queue queue;
public Consumer(Queue queue) {
super();
this.queue = queue;
}
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() == 0) {
System.out.println("queque is empty");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int num = (int) queue.poll();
System.out.println("consume" + num);
queue.notify();
if (num == 3) {
break;
}
}
}
}
public static void main(String args[]) {
Queue queue = new LinkedList();
Producer pro = new Producer(queue);
Consumer consumer = new Consumer(queue);
Thread t1 = new Thread(pro, "pro");
t1.start();
Thread t2 = new Thread(consumer, "con");
t2.start();
}
}