美文网首页
高并发编程三

高并发编程三

作者: 紫雨杰 | 来源:发表于2018-05-15 17:22 被阅读0次

    1、 有N张火车票,每张票都有一个编号,同时有10个窗口对外售票,请写一个模拟程序

    就算操作A和B都是同步的,但A和B组成的复合操作也未必是同步的,仍然需要自己进行同步

    使用Vector或者Collections.synchronizedXXX,分析一下,这样能解决问题吗?能会产生哪些问题?
            public class TicketSeller2 {
                    static Vector<String> tickets = new Vector<>();      //Vector是线程安全的 
                    static {
                          for(int i=0; i<1000; i++) {
                                   tickets.add("票 编号:" + i);
                           } 
                     }
        
                      public static void main(String[] args) {      
                            for(int i=0; i<10; i++) {
                                new Thread(()->{
                                    while(tickets.size() > 0) {     //Vector是线程安全的,size()和remove()方法也是线程安全的     
                                        ry {                        //但是两个同步方法一起使用,不能保证是同步的,所以也会出现错误
                                            TimeUnit.MILLISECONDS.sleep(10);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }                                   
                                        System.out.println("销售了--" + tickets.remove(0));
                                     }
                                }).start();
                            }
                      }
            }
    

    就下面程序,判断size和进行remove必须是一整个的原子操作

            public class TicketSeller2 {
                    static List<String> tickets = new LinkedList<>();   
                    static {
                          for(int i=0; i<1000; i++) {
                                   tickets.add("票 编号:" + i);
                           } 
                     }
        
                      public static void main(String[] args) {      
                            for(int i=0; i<10; i++) {
                                new Thread(()->{
                                    while(true) {   
                                        synchronized(tickets) {
                                            if(tickets.size() <= 0) {
                                                  break;    
                                            }
                                            try {                     
                                                TimeUnit.MILLISECONDS.sleep(10);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }                                   
                                            System.out.println("销售了--" + tickets.remove(0));
                                        }
                                     }
                                }).start();
                            }
                      }
            }
    

    使用ConcurrentQueue提高并发性

         public class TicketSeller2 {
                 static Queue<String> tickets = new ConcurrentLinkedQueue<>();
                 static {
                       for(int i=0; i<1000; i++) {
                                tickets.add("票 编号:" + i);
                        } 
                  }
     
                   public static void main(String[] args) {      
                         for(int i=0; i<10; i++) {
                             new Thread(()->{
                                 while(true) {   
                                     String s = tickets.poll();   //poll()方法是同步的,之后并没有再对票数进行任何操作,只是单纯的判断,所以不会出现问题
                                     if(s == null) {
                                         break;  
                                     } else {                                                
                                         System.out.println("销售了--" + s);
                                     }
                                  }
                             }).start();
                         }
                   }
         }
    

    2、同步容器类

     java5.0在java.util.concurrent包中提供了多种并发容器来改进同步容器的性能; 
    
     ①、ConcurrentMap
         ★ ConcurrentHashMap同步容器类是java5增加的一个线程安全的哈希表。 对与多线程的操作,介于HashMap与Hashtable之间。
            内部采用"锁分段"机制代替Hashtable的独占锁。进而提高性能。
    
         ★ ConcurrentSkipListMap :
            提供了一种线程安全的并发访问的排序映射表。内部是SkipList(跳表)结构实现,在理论上能够O(log(n))时间内完成查找、插入、删除操作。
    
         ● 当期望许多线程访问一个给定collection时,ConcurrentHashMap通常优先于同步的HashMap,ConcurrentSkipListMap通常优先于同步的TreeMap。
    
         ★ ConcurrentSkipListSet
    
     ②、 当期望的读数和遍历远远大于列表的更新数时,CopyOnWriteArrayList优先于同步的ArrayList。
         此外还有CopyOnWriteArraySet
    
         ★ CopyOnWriteArrayList / CopyOnWriteArraySet   "写入并复制"
         ★ 当添加操作多时不适合用CopyOnWriteArrayList/Set。 因为每写入一次就会进行一次复制,效率低,开销大,耗内存。
         ★ 当并发迭代多时,可以选择使用。
    
          默认的并发级别(concurrentLevel = 16 );
    
     ③、Queue:队列
         ★  实现类有13个:AbstractQueue、 ArrayBlockingQueue 、ArrayDeque 、ConcurrentLinkedDeque、ConcurrentLinkedQueue 、
                         DelayQueue、LinkedBlockingDeque 、LinkedBlockingQueue 、LinkedList、LinkedTransferQueue、
                         PriorityBlockingQueue 、 PriorityQueue、 SynchronousQueue  
                         
    
    
         ★ 队列通常(但并非一定)以 FIFO(先进先出)的方式排序各个元素。不过优先级队列和 LIFO 队列(或堆栈)例外,前者根据提供的比较器或元素的自然顺序对元素进行排序,
            后者按 LIFO(后进先出)的方式对元素进行排序。无论使用哪种排序方式,队列的头都是调用 remove()或 poll()所移除的元素。            
         ★ 在 FIFO 队列中,所有的新元素都插入队列的末尾。
         ★ 队列的offer()方法,向队列中添加元素,返回一个boolean值区分是否添加成功,通常要优于 Collection.add(E)方法,该方法只能通过抛出未经检查的异常使添加元素失败
         ★ remove()和poll()方法可移除和返回队列的头。但是在队列为空时其行为有所不同:remove()方法抛出一个异常,而poll()方法则返回 null。 
         ★ element()和peek()返回,但不移除,队列的头。
         ★ Queue 实现通常不允许插入 null 元素
    
    
        (1)、LinkedBlockingQueue叫无界队列,没有界限,往里面添加多少个元素都可以,直到把内存填满为止。
    
          public class LinkedBlockingQueueDemo {
    
                  static BlockingQueue<String> strs = new LinkedBlockingQueue<>();
                  static Random r = new Random();
    
                  public static void main(String[] args) {
                        new Thread(() -> {
                            for (int i = 0; i < 100; i++) {
                                try {
                                    strs.put("a" + i); //如果满了,就会等待
                                    TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, "p1").start();
    
                       for (int i = 0; i < 5; i++) {
                            new Thread(() -> {
                              for (;;) {
                                  try {
                                      System.out.println(Thread.currentThread().getName() + " take -" + strs.take()); //如果空了,就会等待
                                  } catch (InterruptedException e) {
                                      e.printStackTrace();
                                  }
                               }
                             }, "c" + i).start();
                        }
                  }
            }
    
        (2)、ArrayBlockingQueue:有界队列,即容器中装的任务是有限的
    
            public class T06_ArrayBlockingQueue {
    
                  static BlockingQueue<String> strs = new ArrayBlockingQueue<>(10);    //容器中只能装10个元素
                  static Random r = new Random();
                  public static void main(String[] args) throws InterruptedException {
                        for (int i = 0; i < 10; i++) {
                            strs.put("a" + i);
                        }
        
                        strs.put("aaa");     //满了就会等待,程序阻塞,无限制的阻塞下去
                        //strs.add("aaa");   //满了会抛异常
                        //strs.offer("aaa");  //根据Boolean返回值判断是否添加成功
                        //strs.offer("aaa", 1, TimeUnit.SECONDS);   //按时间段阻塞
        
                        System.out.println(strs);
                  }
            }
    
        (3)、DelayQueue:无界队列,默认是排好顺序的,等待时间最长的优先出队列
              ▲ Delayed元素的一个无界阻塞队列,只有在延迟期满时才能从中提取元素。该队列的头部是延迟期满后保存时间最长的Delayed元素。
                如果延迟都还没有期满,则队列没有头部,并且 poll将返回 null。
              ▲ 此队列不允许使用 null 元素。 
              ▲ 要求往里添加的任务必须实现Delayed接口
              ▲ 用于执行定时任务
    
        (4)、LinkedTransferQueue:有一定容量的,使用transer()方法添加的数据不是放在容量中而是直接给消费者
    
        (5)、SynchronousQueue:一种特殊的LinkedTransferQueue,容量为0
              【产生的任何东西必须直接交给消费者去消费,不能放在容器中】
    
              public class SynchronusQueueDemo { //容量为0
                  public static void main(String[] args) throws InterruptedException {
                        BlockingQueue<String> strs = new SynchronousQueue<>();      
                        new Thread(()->{
                            try {
                                  System.out.println(strs.take());
                            } catch (InterruptedException e) {
                                  e.printStackTrace();
                            }
                        }).start();
    
                        //put(): 将指定的元素插入此队列,等待空间变得可用时。底层使用transer实现
                        strs.put("aaa"); //如果put aaa时,必须有一个消费者,然后直接把aaa交给消费者,如果没有消费者了,则会阻塞等待消费者然后进行消费
                        //strs.add("aaa");  //报错
                        System.out.println(strs.size());
                  }
              }
    
     ④、Deque:双端队列
         ★  实现类有三个:ArrayDeque、LinkedBlockingDeque 、LinkedList
    

    相关文章

      网友评论

          本文标题:高并发编程三

          本文链接:https://www.haomeiwen.com/subject/mgevkftx.html