• 生产者消费者(举例)


    线程A:生产者;

    线程B:消费者;

    具体场景:

      线程A调用set(String str),给list里面设置字符串,线程B调用get()方法,删除掉list里面的字符串,模拟生产者消费者

      

     1 package com.test1;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 /**
     7  * 
     8 synchronizd可以作用于代码块和方法块上,现在编写一个生产者和消费者的简单例子。
     9 
    10 功能:
    11 
    12 两个线程A,B。对同一个List进行操作。A写入数据,B读取数据。
    13 A每次写入一个数据,就会通知B去读取。
    14 B每次读取完,就将该数据从List中清除。
    15 当List为空的时候,B会一直等待。
    16  * @author Administrator
    17  *
    18  */
    19 public class ProduceConsume {
    20     List list = new ArrayList();
    21     
    22     public static void main(String[] args) {
    23         final ProduceConsume produceConsume = new ProduceConsume();
    24         Runnable runnable1 = new Runnable() {
    25             
    26             @Override
    27             public void run() {
    28                 produceConsume.set("hello");
    29                 produceConsume.set("world");
    30             }
    31         };
    32         Runnable runnable2 = new Runnable() {
    33             
    34             @Override
    35             public void run() {
    36                 while(true){
    37                     produceConsume.get();
    38                 }
    39             }
    40         };
    41         
    42         new Thread(runnable1).start();
    43         new Thread(runnable2).start();
    44         
    45     }
    46     
    47     public void set(String string){
    48         synchronized (list) {
    49             list.add(string);
    50             list.notifyAll();
    51         }
    52     }
    53     public void get(){
    54         synchronized (list) {
    55             while(list.isEmpty()){
    56                 try {
    57                     list.wait();
    58                 } catch (InterruptedException e) {
    59                     e.printStackTrace();
    60                 }
    61             }
    62             System.out.println("length:"+list.size());
    63             System.out.println(list.get(0));
    64             list.remove(0);
    65         }
    66     }
    67 }
  • 相关阅读:
    开通博客第一天
    Vue 打包配置productionSourceMap 的记录
    supervisorctl 的 简单记录
    mvn打包方式记录
    springboot日志配置,关于logback
    springboot集成swagger
    关于mapper文件的bean
    elasticsearch 连接、操作记录
    关于前后端分离文件上传的些许问题
    代码优化--策略模式的四种表现
  • 原文地址:https://www.cnblogs.com/rgever/p/9642232.html
Copyright © 2020-2023  润新知