Java教程

Java的多线程模型

本文主要是介绍Java的多线程模型,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

https://blog.csdn.net/qq_40550018/article/details/87859399

//商品类
public class Goods {
    private int id;
    private String name;

    public Goods(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
//消费者类
public class Producer implements Runnable {
    private Goods goods;

    @Override
    public void run() {
            while (true) {
                try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        synchronized (TestPC.queue) {

                goods=new Goods(1,"商品");
                if (TestPC.queue.size()<MAX_POOL) {
                    TestPC.queue.add(goods);
                    System.out.println(Thread.currentThread().getName()+"生产商品");

                } else {
                    try {
                        TestPC.queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

//生产者类
public class Consumer implements Runnable {
    @Override
    public void run() {
        while (true){
            try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (TestPC.queue){

            if(!TestPC.queue.isEmpty()){
                TestPC.queue.poll();
                System.out.println(Thread.currentThread().getName()+"消费商品");
            }
            else {
                TestPC.queue.notify();
            }
        }
    }
    }
}
//测试类
public class TestPC {
    public static final int MAX_POOL=10;
    public static final int MAX_PRODUCER=5;
    public static final int MAX_CONSUMER=4;
    public static  Queue<Goods> queue=new ArrayBlockingQueue<>(MAX_POOL);
    public static void main(String[] args) {
        Producer producer=new Producer();
        Consumer consumer=new Consumer();
        for(int i=0;i<MAX_PRODUCER;i++) {
            Thread threadA = new Thread(producer, "生产者线程"+i);
            threadA.start();
        }
        for(int j=0;j<MAX_CONSUMER;j++) {
            Thread threadB = new Thread(consumer, "消费者线程"+j);
            threadB.start();
        }
    }
}


这篇关于Java的多线程模型的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!