用synchronized wait及notify實作 簡單的生産者消費者的例子。以下是代碼部分
/**
* Test.java Create on 2014年10月10日
*
* Copyright (c) 2014年10月10日 by dzh
*
* @author <a href="[email protected]" target="_blank" rel="external nofollow" >xingyu</a>
* @version 0.0.1
*
*/
package org.dzh.thread.waitAndnotify;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**@className:Test.java
* @description
* 線程{@link Thread} 與{@link Object#notify() #wait()} 的用法例子
* 簡單生産者消費者例子
* @date 2014年10月10日 上午11:32:23
*/
public class Test {
private static List<Integer> queue = new ArrayList<>();
/**
* 生産者
* @param n void
*
*/
public synchronized void producer(int n){
System.out.println("insert data "+n);
queue.add(n);
if(queue.size()==1)
this.notify();
}
/**
* 消費者
* @return int
*
*/
public synchronized int consumer(){
try {
if(queue.isEmpty())
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
int result = queue.get(0);
queue.remove(0);
return result;
}
public static void main(String[] args) {
final Test test = new Test();
Thread thread1 = new Thread(new Runnable() {//生産線程
@Override
public void run() {
Random random = new Random();
try {
while(true){
test.producer(random.nextInt(1000));
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {//消費線程
@Override
public void run() {
try {
while(true){
System.out.println("select data is "+test.consumer());
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}