验证中...
gistfile1.txt
原始数据 复制代码
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* 生产者和消费者模式(生产设消费是同一个锁,保证线程安全)
* 汉堡包的店
*/
public class House {
Queue<Hamburger> hamburgers =new LinkedList<Hamburger>();
Object lock =new Object();
public static final int MAX=15;
/**
* 生产
*/
public void pruduce(){
synchronized (lock) {
while(hamburgers.size()==MAX){
try {
System.out.println("生产者正在等待");
lock.wait(); //让持有当前锁对象的线程处于等待状态 ??
} catch (InterruptedException e) {
e.printStackTrace();
}
}
hamburgers.add(new Hamburger());
System.out.println("生产者已经生产了汉堡包");
//通知消费者 吃东西
lock.notifyAll(); //唤醒正在等待此锁的所有线程
}
}
/**
* 消费
*/
public void consume(){
synchronized (lock) {
while(hamburgers.size()==0){
try {
System.out.println("消费者正在等待");
lock.wait(); //让持有当前锁对象的线程处于等待状态 ??
} catch (InterruptedException e) {
e.printStackTrace();
}
}
hamburgers.remove();
System.out.println("消费者已经吃了");
//通知消费者 吃东西
lock.notifyAll(); //唤醒正在等待此锁的所有线程
}
}
public static void main(String[] args) {
House house =new House();
ExecutorService sevice = Executors.newCachedThreadPool();
sevice.submit(new Producer (house) );
sevice.submit(new Consumer (house) );
sevice.submit(new Consumer (house) );
sevice.submit(new Consumer (house) );
sevice.submit(new Consumer (house) );
sevice.submit(new Consumer (house) );
sevice.submit(new Consumer (house) );
sevice.shutdown();
}
}
//汉堡包的类
class Hamburger{
}
//生产者
class Producer implements Runnable{
House house;
Producer(House house){
this.house=house;
}
@Override
public void run() {
while(true){
house.pruduce();
//休息一下
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class Consumer implements Runnable{
House house;
Consumer(House house){
this.house=house;
}
@Override
public void run() {
int i =0;
while(i<10){
house.consume();
//休息一下
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
}
}

评论列表( 0 )

你可以在登录后,发表评论

11_float_left_people 11_float_left_close