[Multithreading] project combat multithreading

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/wrs120/article/details/90634863

  Demand is this: recently doing a project related to school examinations, which may be classroom teachers several disciplines, each discipline there are several in the class, after the exam, students answer the teacher wants to print paper (because it is on test) , that is related to the batch printing papers, and download these papers labeled as a compressed package, this feature is used in a multi-threaded

1. Why use multithreading

  Make full use of cpu resources

2. When using multiple threads

  1. High concurrency: The system accepts achieving high concurrent multi-user multi request, be achieved through multi-threading.
  2. Thread a large background processing tasks: a linear program is executed. If the program perform a task to spend a lot of time to deal with, that you have to wait for the main program to continue executing the following. That user would have to wait for it to finish execution. This time we can spend a lot of time to open a thread processing tasks on the thread, so that when a thread in the background processing, the main program can continue execution, users do not need to wait. After the execution thread executes the callback function.
  3. Big Task: big deal with time-consuming task, this time you can play multiple threads in parallel to speed up the process (for example: part uploading). For example, to spend a lot of time dealing with a for loop, you can consider multithreading

3. Multi-thread coding project combat

Let me talk about the knowledge used for this function:

  1. Thread Pool
  2. Thread
  3. CountDownLatch
//1.CountDownLatch,计数
CountDownLatch doneSignal = new CountDownLatch(1000);

//2.创建线程池来存放线程,以防考生数量太多创建太多线程,占用过多资源
ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 150, 60000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());

for (ExaminationModel examineeModel : notExamStudentInfo) {
	。。。。。。
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
           。。。。。。打印试卷的逻辑
            } finally {             
            	// 每执行完一个线程,数量减1      
                doneSignal.countDown();
            }
        }
    });
    //3. 将任务添加到线程池
    executor.execute(thread);
}

//  4. 为了让所有的试卷都生成之后再执行压缩以及删除PDF文件,所以需要让主线程等待子线程执行完之后再执行await
try {
	// 主线程等待
    doneSignal.await();
    System.out.println("线程运行时间:" + (System.currentTimeMillis() - startTime) + "ms");
} catch (InterruptedException e) {
    log.error(e.getMessage(), e);
}

//5. 关闭线程池(所有线程执行完关闭线程池)
executor.shutdown();

// 6. 将所有试卷打包zip
boolean flag = fileToZip();

Realization of ideas:
  create a thread pool, and thread lock counter, print a copy of every paper is a task that will add missions to the thread pool, and then thread execution, when all the papers have been printed, all the papers in a zip

Knowledge points to explain:

  1. The reason to use the thread pool, because the threads to prevent excessive, resulting in a thread switch back and forth, loss caused by the formation of
  2. CountDownLatch: its role is to allow 1 or N threads waiting for other threads to complete execution, in which it is used as to put all the papers, a zip archive, so the main thread to wait for all child threads to be executed which generates paper to finish packing, uses CountDownLatch the await () and countDown () method, to explain more about the CountDownLatch, see: https://www.cnblogs.com/skywang12345/p/3533887.html
  3. I created this core thread is 50, maximum 150 threads, more computer cpu performance settings, print executor thread number, thread number has been over 50, however, because the task queue using LinkedBlockingDeque, size Integer.MAX_VALUE (Integer .MAX_VALUE = 7fffffff (hex) = 2147483647 (decimal)), has the task queue is not full , the specific reasons for details, see: https://mp.csdn.net/mdeditor/90082697#

4. Why not join ()

Use join () problems that may occur:

  1. join () may be completed later in the code in advance, so that the whole data is not packed
  2. join () process may be interrupted, so that the system will throw an exception (because the underlying call is wait ()), if you do not have to let the program do all kinds judge determine an abnormality, more trouble

Guess you like

Origin blog.csdn.net/wrs120/article/details/90634863