多线程之间的通讯方式-生产和消费(包括连续的生产和消费demo01实现)

DEMO01:

/**
 * 使用Object wait notify 控制线程通信(第一种方式)
 *
 * 并实现生产--》提货--》再次生产---》再次提货的循环体系,加载sleep时间,类似定时器,
 * 但是有区别,本实例在不同的线程执行,有生产线程,有消费线程
 */
public class ObjectWaitNotify {
    static Object object=new Object();
    public static List<String> list=new ArrayList();
    public static void main(String[] args) {
        new Thread(() -> {
           while (true){
               synchronized (object){
                   try {
                       System.out.println("等待供货商通知取货----");
                       object.wait();
                       System.out.println("收到通知,可以提货");
                       if(list.size()>=4){
                           list.stream().forEach(s -> System.out.println("取出所有的包子--"+s));
                       }
                       System.out.println("已提取所有的货物---");
                       System.out.println("清空仓库----");
                       list.clear();
                       object.notifyAll();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
           }
        },"线程B").start();


        new Thread(() -> {
                synchronized (object){
                    System.out.println("当前正在备货中-----");
                    for (int i = 0; i < 4; i++) {
                        list.add("包子"+i);
                    }

                    System.out.println("通知代理商取货---");
                    object.notifyAll();

                    try {
                        object.wait();
                        Thread.sleep(100);
                        while (true){
                            Thread.sleep(2000);
                            System.out.println("等待代理商取货,取货后再次生产---");
                            if(list.size()==0){
                                for (int i = 0; i < 4; i++) {
                                    list.add("包子"+i);
                                }
                                System.out.println("通知代理商取货---");
                                object.notifyAll();
                                object.wait();
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        },"线程A").start();
    }
}

DEMO02

/**
 * 线程间通信第二种方式,使用lock  和Condition方式
 */
public class LockCondition {
    private  static Lock lock=new ReentrantLock();
    private  static Condition condition = lock.newCondition();
    public static List<String> list=new ArrayList();
    public static void main(String[] args) {
        new Thread(() -> {
            while (true){
                lock.lock();
                try {
                    System.out.println("等待供货商通知取货----");
                    condition.await();
                    System.out.println("收到通知,可以提货");
                    if(list.size()>=4){
                        list.stream().forEach(s -> System.out.println("取出所有的包子--"+s));
                    }
                    System.out.println("已提取所有的货物---");
                    break;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.unlock();
            }
        },"线程B---消费线程").start();


        new Thread(() -> {
            lock.lock();
            System.out.println("当前正在备货中-----");
            for (int i = 0; i < 4; i++) {
                list.add("包子"+i);
            }
            System.out.println("通知代理商取货---");
            condition.signal();
            lock.unlock();
        },"线程A--生产线程").start();
    }
}

DEMO03

/**
 * 线程通讯的第三种方式 ---这是最简单的方式
 */
public class VolatileCommunicate {
    private static volatile Boolean flag=false;
    public static List<String> list=new ArrayList();
    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println("等待供货商通知取货----");
            while (true){
                if(flag){
                    System.out.println("收到通知,可以提货");
                    if(list.size()>=4){
                        list.stream().forEach(s -> System.out.println("取出所有的包子--"+s));
                    }
                    System.out.println("已提取所有的货物---");
                    break;
                }
            }
        },"线程B---消费线程").start();

        new Thread(() -> {
            System.out.println("当前正在备货中-----");
            for (int i = 0; i < 4; i++) {
                list.add("包子"+i);
            }
            System.out.println("通知代理商取货---");
            flag=true;
        },"线程A--生产线程").start();
    }
}

 

DEMO04

/**
 * CountDownLatch  实现线程之间的通讯
 */
public class CountDownLatchCommunicate {
    private static CountDownLatch countDownLatch = new CountDownLatch(4);
    public static  List<String> list=new ArrayList();
    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println("1号消费者-等待供货商通知取货----");
            while (true){
                try {
                    countDownLatch.await();
                    System.out.println("1号消费者-收到通知,可以提货");
                    if(list.size()>=4){
                        synchronized (list){
                            Iterator<String> iterator = list.iterator();
                            boolean conusmer=false;
                            while (iterator.hasNext()){
                                System.out.println("1号消费者-取出所有的包子--"+iterator.next());
                                iterator.remove();
                                System.out.println("1号消费者提取后》》当前存货是="+list.size());
                                if(!conusmer){
                                    conusmer=true;
                                }
                            }
                            if(conusmer){
                                System.out.println("1号消费者-已提取所有的货物---");
                            }else {
                                System.out.println("货物已被其他2号消费者抢光了");
                            }
                        }
                    }
                    break;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程B---消费线程1").start();

        new Thread(() -> {
            System.out.println("2号消费者-等待供货商通知取货----");
            while (true){
                try {
                    countDownLatch.await();
                    System.out.println("2号消费者-收到通知,可以提货");
                    if(list.size()>=4){
                        synchronized (list){
                            Iterator<String> iterator = list.iterator();
                            boolean conusmer=false;
                            while (iterator.hasNext()){
                                System.out.println("2号消费者-取出所有的包子--"+iterator.next());
                                iterator.remove();
                                System.out.println("2号消费者提取后》》当前存货是="+list.size());
                                if(!conusmer){
                                    conusmer=true;
                                }
                            }
                            if(conusmer){
                                System.out.println("2号消费者-已提取所有的货物---");
                            }else {
                                System.out.println("货物已被其他1号消费者抢光了");
                            }
                        }
                    }
                    break;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程B---消费线程2").start();


        new Thread(() -> {
            System.out.println("当前正在备货中-----");
            for (int i = 0; i < 4; i++) {
                list.add("包子"+i);
                countDownLatch.countDown();
            }
            System.out.println("通知代理商取货---");
        },"线程A--生产线程").start();
    }
}

 

DEMO05

/**
 * 使用 LockSupport 实现线程间通信
 */
public class LockSupportCommunicat {

    public static List<String> list=new ArrayList();
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("等待供货商通知取货----");
            while (true) {
                LockSupport.park();
                System.out.println("收到通知,可以提货");
                if (list.size() >= 4) {
                    list.stream().forEach(s -> System.out.println("取出所有的包子--" + s));
                }
                System.out.println("已提取所有的货物---");
                break;
            }
        }, "线程B---消费线程");
        thread.start();

        new Thread(() -> {
            System.out.println("当前正在备货中-----");
            for (int i = 0; i < 4; i++) {
                list.add("包子"+i);
            }
            System.out.println("通知代理商取货---");
            LockSupport.unpark(thread);
        },"线程A--生产线程").start();
    }
}

转载请注明出处,全部原创,验证可行才写的博客。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Linux中,可以使用C语言的条件变量和线程来实现消费-生产者模型。下面是一个简单的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define BUFFER_SIZE 10 int buffer[BUFFER_SIZE]; int count = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_prod = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_cons = PTHREAD_COND_INITIALIZER; void *producer(void *arg) { int item = 0; while (1) { pthread_mutex_lock(&mutex); // 如果缓冲区已满,则等待消费消费 while (count == BUFFER_SIZE) { pthread_cond_wait(&cond_prod, &mutex); } buffer[count] = item; count++; printf("Producer produced item %d\n", item); // 唤醒消费线程 pthread_cond_signal(&cond_cons); pthread_mutex_unlock(&mutex); item++; } pthread_exit(NULL); } void *consumer(void *arg) { while (1) { pthread_mutex_lock(&mutex); // 如果缓冲区为空,则等待生产生产 while (count == 0) { pthread_cond_wait(&cond_cons, &mutex); } int item = buffer[count - 1]; count--; printf("Consumer consumed item %d\n", item); // 唤醒生产线程 pthread_cond_signal(&cond_prod); pthread_mutex_unlock(&mutex); } pthread_exit(NULL); } int main() { pthread_t producer_thread, consumer_thread; // 创建生产者和消费线程 pthread_create(&producer_thread, NULL, producer, NULL); pthread_create(&consumer_thread, NULL, consumer, NULL); // 等待线程结束 pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); return 0; } ``` 在上面的代码中,生产线程不断地向缓冲区中生产数据,而消费线程不断地从缓冲区中消费数据。当缓冲区满时,生产线程会等待条件变量`cond_prod`,直到有消费消费数据才会被唤醒。同样,当缓冲区为空时,消费线程会等待条件变量`cond_cons`,直到有生产生产数据才会被唤醒。 需要注意的是,在生产者和消费线之间共享的变量`count`和`buffer`需要进行互斥访问,因此使用了互斥锁`mutex`来保护共享资源的访问。 希望这个示例能帮助你理解如何在Linux中使用C语言的条件变量和线实现消费-生产者模型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值