https://www.cnblogs.com/chengxiao/p/6528109.html volatile关键字
http://www.importnew.com/16453.html waite()和notify()实现生产者和消费者队列
/**
* 生产者
* @author ZXS
*
*/
public class Product implements Runnable{
private LinkedList<Integer> list;
public Product(LinkedList<Integer> list) {
this.list = list;
}
@Override
public void run() {
while (true) {
synchronized (list) {
while (list.size() == 100) {
try {
System.out.println("生产者" + Thread.currentThread().getId() +"生产已满");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int i = new Random().nextInt();
System.out.println("生产者" + Thread.currentThread().getId() +"生产了一个数字:" + i);
list.add(i);
list.notifyAll();
}
}
}
}
package thread;
import java.util.LinkedList;
/**
* 消费者
* @author ZXS
*
*/
public class Consumer implements Runnable{
private LinkedList<Integer> list;
public Consumer(LinkedList<Integer> list) {
this.list = list;
}
@Override
public void run() {
while (true)
{
synchronized (list) {
while (list.isEmpty()) {
try {
System.out.println("生产者已经空!");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consumer消费者" + Thread.currentThread().getId() +" 消费了一个数字:" + list.remove() );
list.notifyAll();
}
}
}
}
package thread;
import java.util.LinkedList;
/**
* 线程间的通信 wait 和 notify 使用
* @author ZXS
*
*/
public class ThreadTest1
{
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
Thread cousumer1 = new Thread(new Consumer(list));
Thread product = new Thread(new Product(list));
Thread cousumer2 = new Thread(new Consumer(list));
product.start();
cousumer1.start();
cousumer2.start();
}
}