多线程处理同一个List测试dome

摘要:
此外,await()方法还有一个实用的重载方法:publicfoleanawait,它设置超时。例如,上面的代码希望将超时设置为10秒。当超时达到10秒时,无论倒计时是否完成到0,主线程都将不再被阻塞。主线程等待线程池Java线程池Java.util.concurrent.ExecutorService是一种很好的多线程管理方法。ExecutorService的一种方法,boolean awaitTermination,是阻塞主线程并等待线程池中的所有线程完成执行。用法类似于上述CountDownLatch的publicboolean awaitof。该参数设置超时时间,返回值为布尔类型。如果超时为false,并且线程池中的所有线程都已完成执行,则返回true。
package com.sysware.p2m.task.op.process;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ThreadTese{

  static   class TestRnnubeal extends Thread{
        private String threadName;
        private List<String> list;
        private int startIndex;
        private int endIndex;
        private CountDownLatch countDownLatch;//计数器


      public TestRnnubeal(String threadName, List<String> list, int startIndex, int endIndex,CountDownLatch countDownLatch) {
          this.threadName = threadName;
          this.list = list;
          this.startIndex = startIndex;
          this.endIndex = endIndex;
          this.countDownLatch = countDownLatch;
      }
        public void run() {
            List<String> subList = list.subList(startIndex, endIndex);
            for(int i=0;i<subList.size();i++){
        //        System.out.println(i);
            }
            System.out.println(threadName+"处理了"+subList.size()+"条!startIndex:"+startIndex+"|endIndex:"+endIndex);
            countDownLatch.countDown();//计数器减1
        }
    }


    public static void main(String[] args) {
        long strTime2 = System.currentTimeMillis();
        List<String> tmpList = new ArrayList<String>();
        for (int i = 0; i < 13000000; i++) {
            tmpList.add("test" + i);
        }

        int length = tmpList.size();
        int num = 10; //初始线程数

        //启动多线程
        if(num > length){
            num = length;
        }
        int baseNum = length / num;
        int remainderNum = length % num;
        int end  = 0;
        long end2 = System.currentTimeMillis();

        long strTime = System.currentTimeMillis();
        List<Thread> list =new ArrayList<Thread>();
        CountDownLatch countDownLatch = new CountDownLatch(num); //创建一个线程计数器 传入线程数
        for (int i = 0; i < num; i++) {
            int start = end ;
            end = start + baseNum;
            if(i == (num-1)){
                end = length;
            }else if( i < remainderNum){
                end = end + 1;
            }

                 Thread thread = new TestRnnubeal("线程[" + (i + 1) + "] ",  tmpList,start , end,countDownLatch);
                 thread.start();
       //          list.add(thread); //也可以使用join方法;
        }

//        for (Thread thread:list){
//            try {
//                thread.join();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
     //   }
      
      
  try {
            boolean timeoutFlag = countDownLatch.await(50, TimeUnit.SECONDS);//设置线程超时时间 同await()一样;
            if (timeoutFlag) {
               System.out.println("所有线程执行完毕");
            }else {
                System.out.println("执行超时");
            }
            //   countDownLatch.await();//阻止主线程 当计数器为0时放开(说明所有子线程以执行完毕)
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
long endTime = System.currentTimeMillis(); System.out.println("用时"+ (endTime-strTime) + "毫秒"+"处理数据用时"+(end2-strTime2)+"毫秒"); } }

注意:如果子线程中会有异常,那么countDownLatch.countDown()应该写在finally里面,这样才能保证异常后也能对计数器减1,不会让主线程永远等待。

另外,await()方法还有一个实用的重载方法:public booleanawait(long timeout, TimeUnit unit),设置超时时间。

例如上面的代码,想要设置超时时间10秒,到了10秒无论是否倒数完成到0,都会不再阻塞主线程。返回值是boolean类型,如果是超时返回false,如果计数到达0没有超时返回true。

主线程等待线程池

Java线程池java.util.concurrent.ExecutorService是很好用的多线程管理方式。ExecutorService的一个方法boolean awaitTermination(long timeout, TimeUnit unit),即阻塞主线程,等待线程池的所有线程执行完成,用法和上面所说的CountDownLatch的public boolean await(long timeout,TimeUnit unit)类似,参数设置一个超时时间,返回值是boolean类型,如果超时返回false,如果线程池中的线程全部执行完成,返回true。

由于ExecutorService没有类似CountDownLatch的无参数的await()方法,只能通过awaitTermination来实现主线程等待线程池。

public class Main  
{  
    public static void main(String[] args)  
    {  
        long start = System.currentTimeMillis();  
          
        // 创建一个同时允许两个线程并发执行的线程池  
        ExecutorService executor = Executors.newFixedThreadPool(2);  
        for(int i = 0; i < 5; i++)  
        {  
            Thread thread = new TestThread();  
            executor.execute(thread);  
        }  
        executor.shutdown();  
          
        try  
        {  
            // awaitTermination返回false即超时会继续循环,返回true即线程池中的线程执行完成主线程跳出循环往下执行,每隔10秒循环一次  
            while (!executor.awaitTermination(10, TimeUnit.SECONDS));  
        }  
        catch (InterruptedException e)  
        {  
            e.printStackTrace();  
        }  
          
        long end = System.currentTimeMillis();  
        System.out.println("子线程执行时长:" + (end - start));  
    }  
}

免责声明:文章转载自《多线程处理同一个List测试dome》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android Q dynamic partition三、五种IO模型透彻分析下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

超全!iOS 面试题汇总

作者:Job_Yang 之前看了很多面试题,感觉要不是不够就是过于冗余,于是我将网上的一些面试题进行了删减和重排,现在分享给大家。(题目来源于网络,侵删) 1. Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么? 答: Object-c的类不可以多重继承;可以实现多个接口,通过实现多...

c++中CreateEvent函数

参考:https://blog.csdn.net/u011642774/article/details/52789969 函数原型: [cpp] view plain copy  HANDLE CreateEvent(     LPSECURITY_ATTRIBUTES lpEventAttributes, // SD     BOOL bMan...

开源微内核seL4

微内核 越大的系统潜在的bug就越多。所以微内核在降低bug方面非常有优势,seL4是世界上最小的内核之中的一个。可是seL4的性能能够与当今性能最好的微内核相比。 作为微内核,seL4为应用程序提供少量的服务。如创建和管理虚拟内存地址空间的抽象,线程和进程间通信IPC。这么少的服务靠8700行C代码搞定。seL4是高性能的L4微内核家族的新产物,它具...

MySQL锁问题

MySQL锁问题 MySQL的锁机制比较简单,其最显著的特点是不同的存储引擎支持不同的锁机制。比如,MyISAM和MEMORY存储引擎 采用的是表级锁;BDB存储引擎采用的是页面锁,但也支持表级锁;InnoDB存储引擎既支持行级锁,也支持表级锁,但默认 情况下采用行级锁。 MySQL这3种锁的特性可大致归纳如下: (1)表级锁:开销小...

阿里P6初面Java面试题,附带完整答案,赶紧搜藏

最强面试题推荐: 2020Java面试题及答案,命中率高达90% 1、锁可以锁在哪里? Java 为程序加锁的方式主要有两种:synchronized 与 Lock。 1. synchronized 可以修饰的作用域如下: - 非静态方法(加的锁为对象锁); - 静态方法(加的锁为类锁); - 代码块(对象锁与类锁均可); 2. Lock 采用 lock(...

Web Worker 使用教程

Web Worker 使用教程 一、概述 JavaScript 语言采用的是单线程模型,也就是说,所有任务只能在一个线程上完成,一次只能做一件事。前面的任务没做完,后面的任务只能等着。随着电脑计算能力的增强,尤其是多核 CPU 的出现,单线程带来很大的不便,无法充分发挥计算机的计算能力。 Web Worker 的作用,就是为 JavaScript 创造多...