请大佬指教

大佬看看这个代码怎么样


以下是一个简单的Java多线程生产者-消费者模型代码实现:

```java

import java.util.LinkedList;

public class ProducerConsumerExample {

    public static void main(String[] args) throws InterruptedException {

        final PC pc = new PC();

        Thread t1 = new Thread(new Runnable() {

            @Override

            public void run() {

                try {

                    pc.produce();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        });

        Thread t2 = new Thread(new Runnable() {

            @Override

            public void run() {

                try {

                    pc.consume();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        });

        t1.start();

        t2.start();

        t1.join();

        t2.join();

    }

    public static class PC {

        LinkedList<Integer> list = new LinkedList<>();

        int capacity = 2;

        public void produce() throws InterruptedException {

            int value = 0;

            while (true) {

                synchronized (this) { 

                    while (list.size() == capacity)

                        wait();

                    System.out.println("Producer produced-" + value);

                    list.add(value++);

                    notify();

                    Thread.sleep(1000);   

                }

            }

        }

        public void consume() throws InterruptedException {

            while (true) {

                synchronized (this) { 

                    while (list.size() == 0)

                        wait();

                    int val = list.removeFirst();

                    System.out.println("Consumer consumed-" + val);

                    notify();

                    Thread.sleep(1000);

                }

            }

        }

    }

}

```

这段代码实现了一个生产者-消费者模型,多个线程同时访问一个共享的数据结构,并通过wait和notify方法进行同步和协调,实现线程之间的合作和协作。生产者生产数据并加入到列表中,消费者从列表中取出数据并消费。



请大佬指教

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容