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

来源:互联网 发布:华为移动数据快捷开关 编辑:程序博客网 时间:2024/06/14 11:09

根据自己的理解简单的实现了一个,生产者,消费者模式的多线程,请大家多提宝贵意见
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();}

}

原创粉丝点击