日期:2014-05-20 浏览次数:20725 次
public class Baskert {
private List<String> list = new ArrayList<String>();
private Lock lock = new ReentrantLock();
private Condition setter = lock.newCondition(); //篮子为满的条件
private Condition getter = lock.newCondition(); //篮子为空的条件
public void addApple() throws InterruptedException{
try{
lock.lock();
while(list.size()>=5){
System.out.println(Thread.currentThread().getName()+"--挂起");
setter.await();
}
list.add("红富士");
System.out.println(Thread.currentThread().getName()+"放了一个红富士==="+list.size());
System.out.println("释放2,3");
getter.signalAll();
}finally{
lock.unlock();
}
}
public void removeApple() throws InterruptedException{
try{
lock.lock();
while(list.size()<=0){
System.out.println(Thread.currentThread().getName()+"--挂起");
getter.await();
}
list.remove(0);
System.out.println(Thread.currentThread().getName()+"拿了一个苹果==="+list.size());
System.out.println("释放0,1");
setter.signalAll();
}finally{
lock.unlock();
}
}
public static void main(String[] args){
final Baskert baskert = new Baskert();
new Thread(new Runnable() {
public void run() {
try {
while(true){
baskert.addApple();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
while(true){
baskert.addApple();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
while(true){
baskert.removeApple();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
while(true){
baskert.removeApple();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 多线程生产者-消费者示例
*/
public class Basket {
public static final int BASKET_CAPACITY = 5;
private List<String> list = new ArrayList<>();
private Lock lock = new ReentrantLock();
private Condition setter = lock.newCondition(); //篮子为满的条件
private Condition getter = lock.newCondition(); //篮子为空的条件
// 放入苹果
public void addApple() throws InterruptedException {
try {
lock.lock();
while (list.size() >= BASKET_CAPACITY) {
outputThreadMessage("篮子已满,等待取出", false);
setter.await();
}
list.add("红富士");
outputThreadMessage("放入苹果: 篮子里还有" + list.size(), false);
getter.signalAll();
} finally {
lock.unlock();
}