Java多线程实现,生产者消费者

根据自己的理解简单的实现了一个,生产者,消费者模式的多线程,请大家多提宝贵意见
sleep() wait()比较
sleep()是Thread的静态方法,是用来修改线程自身的运行方式。线程睡眠时间不会释放锁,睡眠完成自动开始执行。
wait()是Object类中的方法,用作线程之间的通信,被其他线程调用notify()方法或notifyAll()方法唤醒。
notify()与notifyAll()比较
notify()是排队唤醒,按顺序唤醒waiting的线程。
notifyAll()是唤醒全部waiting的线程。
//仓库
public class SourceA {

private static int SIZE = 1;
private List<String> list=new ArrayList();

public boolean isEmpty(){
    return list.size()==0?true:false;
}
public boolean isFull(){
    return list.size()<SIZE?false:true;
}
public void getSource(){
    System.out.println("GET A");
    list.remove(0);
}
public void setSource(String str){
    System.out.println("set A");
    list.add(str);
}

}

//生产者
public class SetSource implements Runnable {

private SourceA A;
public SetSource(SourceA A){
    this.A = A;
}
public void run() {

    while(true){
    //多仓库加锁
        synchronized (A) {
            if(A.isFull()){
            //如果仓库满了,通知其他线程
                A.notify();
                try {
                //
                    A.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else{
                A.setSource("A");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

}

//消费者
public class GetSource implements Runnable {

private SourceA A;
public GetSource(SourceA A){
    this.A = A;
}
public void run() {
    synchronized (A) {
        while(true){
        //如果仓库为空,通知其他线程
            if(A.isEmpty()){
                A.notify();
                try {
                    A.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                A.getSource();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }
}

}

//测试
public class Testsg {

public static void main(String[] args) {
    SourceA A = new SourceA();
    GetSource getter = new GetSource(A);
    SetSource setter = new SetSource(A);
    Thread t1 = new Thread(getter, "消費者");
    Thread t2 = new Thread(setter, "生產者");
    Thread t3 = new Thread(setter, "生產者");
    t1.start();
    t2.start();
    t3.start();
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值