This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

Lei Xuewei interesting talk programming – reveal secret large shoe factory million production capacity insider

After xiao Bai visited Wang’s shoes factory together last time, he went back to do a good job of code engineering.

At the same time also greatly shocked, Mr. Wang this shoe factory monthly sales million, that calculated down to have 10,000 pairs of shoes every day, right? (the small white mathematics is afraid is not the physical education teacher teaches!!

And in such large quantities, how does it do that? Can this idea be applied to programming?

Wow, that’s a very creative question!

Wow, the ray school committee thinks that multithreading this piece is very important, a lot of small white write a lot of code, always stay in CRUD or write method to overturn data, simply can’t improve!

Here is a short video recorded by the school committee:

“Lei Learning committee interesting programming story assembly” series of multi-threaded foundation

The following school committee continues to explain the shoe factory assembly line.

Let’s take another look at the production line of a big shoe factory

The picture below shows workers in a packing section of the production line. Cute girls are packing shoes carefully (what a bright smile!).



Image from,The dongguan shoe factory will set up 12 production lines in Guizhou, employing more than 2,400 people

Xiao Bai, you see this workshop is not a lot of people, a lot of shoes.

If you produce 10,000 pairs of shoes, 100 employees, one person gets 100 pairs of shoes, and you work an eight-hour day, that’s 12.5 pairs of shoes per hour, okay

10,000/100/8 = 12.5Copy the code

But selling a million pairs of shoes a month, over a 22-day working day, comes to 56.8 shoes per hour. That’s one shoe per minute!

10000000/22/100/8 = 56.8Copy the code

However, in reality, it is likely that the factory does not employ as many workers for the same amount of work, but handles the amount and works longer hours. It is quite hard!

Check out the video below, it’s been busy!



Screenshot from the video:The actual production line in the shoe factory, the original is made like this, really let me open my eyes!

Small white at the moment is not very happy, looking at a little distressed workers friends. But he is sober, he thinks that should continue to study, complain useless rather than improve themselves, in the future to play more positive role!

He went on to ask, “Why don’t you just automate the assembly line of life? How does it work?” I want to learn!

Ok, please be patient and study hard.

What is Thread (Thread), not ready-made!

To put it in perspective, every labouring worker is like a thread, and then 33,000 pairs of shoes is a daily workload. Running for 21 days, it can produce nearly a million pairs of shoes. (Later will implement this code! Small white must collect more run, master, this is to become a senior programmer must step through the kan)

Threads can be thought of as subtasks that run independently within a Java process. A process is a single run of a program with certain independent functions on a set of data. It is the basic unit of dynamic execution of the operating system. In the traditional operating system, the process is both the basic unit of allocation and the basic unit of execution.

Here is an implementation of a thread in Java:

package org.levintech.javademo.leixuewei.multithread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/** * a simple worker thread **@authorLevin * Created on 2021/7/10 * [lei School Committee] CSDN/Juejin Code Demo */
public class SimpleWorker extends Thread {
    private String workerName;
    private Integer batchSize;

    public SimpleWorker(String workerName, Integer batchSize) {
        this.workerName = workerName;
        this.batchSize = batchSize;
    }

    @Override
    public String toString(a) {
        return "SimpleWorker{" +
                "workerName='" + workerName +
                ",batchSize='" + batchSize +
                '} ';
    }

    @Override// Override the run method to process thread business
    public void run(a) {
        System.out.println("[Lei School Committee Code Demo] workers" + toString());
    }

    public String getWorkerName(a) {
        return workerName;
    }

    public Integer getBatchSize(a) {
        returnbatchSize; }}Copy the code

There are several ways to define threads, and this article will focus on just one! If you know anything, you can check your knowledge in the comments section.

Run the project “LeiXueWeiRunner” to see how it works:



I see there is a state, is it a state?

Yes, threads, like workers, can be in a state, can be vibrant, and can be exhausted.

There are altogether 6 thread states, as shown in the figure below:



If a new Thread is created or a class is inherited, it is a new state. Then the thread is in the RUNNABLE state after the start call and ends without anything else?

Lei: Yes, that’s right. When a thread waits on another thread (for example, when the join method is called), it becomes a wait state (WAITING or TIMED_WAITING). A thread is BLOCKED if its execution requires it to acquire a locked resource.

Does the small white seem to not quite understand the blocking state?

For example, if you only have one set of keys in your house, and you use this set of keys to open several cabinets, but your sister is using it to open closet A, did you not send it to open closet B? She’ll have to give you the key when she’s done. If she finished the thing, ran out to play, ha ha ha, that result you this thread has been waiting!!

B: Yes, I see. (Xiao Bai nods vigorously)

Official to thread state is introduced here: docs.oracle.com/javase/8/do…

Well, you’ve mastered the basics of multithreading, you’ve learned how to create a thread and know its state, and now you’re ready to triple!

Let’s look directly at how the million dollar order is processed.

The following committee wrote a new class (inherited the ordinary workers), in fact, “senior” workers or workers, everyone is the same, should work together to do a good job in the working atmosphere!

Are you ready, white? Lei xuewei to directly on the most difficult code. (The small white estimate can only understand a story, the code he estimated next time to ask!)

Small white confidence full, above so simple, the next estimate won’t be difficult to which go.

The following is the code implementation of the senior worker, before you see the code parsing, please think about why to write this?

/** * a "high level" worker thread **@authorLevin * Created on 2021/7/10 * [lei School Committee] CSDN/Juejin Code Demo */
public class Worker extends SimpleWorker {
    private LinkedBlockingQueue<Integer> workItems;
    private ConcurrentHashMap<String, List<Integer>> status;

    public Worker(String workerName, Integer batchSize, LinkedBlockingQueue<Integer> workItems, ConcurrentHashMap<String, List<Integer>> status) {
        super(workerName, batchSize);
        this.workItems = workItems;
        this.status = status;
    }

    @Override
    public String toString(a) {
        return "Worker{" +
                "workerName='" + super.getWorkerName() +
                ",batchSize='" + super.getBatchSize() +
                ",thread=" + super.getName() +
                ",threadId=" + super.getId() +
                ",threadPriority=" + super.getPriority() +
                ",threadState=" + super.getState() +
                ",threadGroup=" + super.getThreadGroup() +
                ",threadUncaughtExceptionHandler=" + super.getUncaughtExceptionHandler() +
                '} ';
    }

    @Override
    public void run(a) {
        System.out.println("[Lei School Committee Code Demo] workers" + toString());
        int handledNum = 0;
        List<Integer> items = new ArrayList<>();
        while (handledNum < this.getBatchSize() && ! workItems.isEmpty()) {int shoeId = workItems.poll();
            System.out.println("[Lei School Committee Code Demo]" + this.getWorkerName() + "Packed shoes, serial number =" + shoeId);
            handledNum++;
            items.add(shoeId);
        }
        status.put(this.getWorkerName(), items); }}Copy the code

Here is the calling code:

package org.levintech.javademo.leixuewei.multithread;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

import static org.levintech.javademo.leixuewei.multithread.LeiXueWeiRunner01.doAndPrintWorkItem;
import static org.levintech.javademo.leixuewei.multithread.LeiXueWeiRunner01.generateWorkItems;

/ * * *@authorLevin * Created on 2021/6/19 * [lei School Committee] CSDN/Juejin Code Demo */
public class LeiXueWeiRunner02 {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("[Lei School Committee Code Demo]");
        final int totalCount = 1000000;
        LinkedBlockingQueue<Integer> workItems = generateWorkItems(totalCount);// Generate 1 million pairs of shoes
        ConcurrentHashMap<String, List<Integer>> status = new ConcurrentHashMap<>();
        //doAndPrintWorkItem(workItems);
        for (int i = 0; i < 100; i++) {
            Worker leiXiaoHua = new Worker("Ray Floret" + (i + 1), 22 * 8 * 57, workItems, status);
            leiXiaoHua.start();
        }
        while(! workItems.isEmpty()) { System.out.println("The workers are busy working, do not rush, please wait patiently! . The rest," + workItems.size());
            Thread.sleep(3 * 1000);
        }
        int actualTotalCount = 0;
        for (Map.Entry<String, List<Integer>> entry : status.entrySet()) {
            actualTotalCount += entry.getValue().size();
        }
        System.out.println("totalCount="+ actualTotalCount); }}Copy the code

At this time small white face meng!

Code parsing

Here the student committee creates a thread-safe LinkedBlockingQueue and a ConcurrentHashMap that keeps track of the worker’s work.

Then create 100 workers (with a job id, the maximum number of packages each worker can handle, to receive the shoes queue, to receive the map of work status feedback), who will process the shoes on the queue almost simultaneously and complete the packaging

In the Woker class, each employee will check whether the workload of the month is up to the handledNum, if not, continue packing, can go to rest. Or there are no shoes on the assembly line, so it’s time to take a break. Before you break, fill out a form to keep track of how much you’ve accomplished.

Finally, in the main program LeiXueWeiRunner02, it is actually running at the same time with other 100 workers, but it keeps waiting for all shoes to be processed (the situation of queue empty), and then checks the performance of each worker to find out whether there is a missed order.

The program finally checked the result for 1 million, with the original generation of 1 million match! (Well worth a triple here, it’s not an easy program)

Small white say: understand reason, the code still have to see much, not too familiar (I see he had never used.

The whole process is the same as below, but I suggest you watch more videos after three consecutive:



Knock on the board, can readers do the same?

You need to work on this! The committee is only responsible for the article, but you are responsible for yourself! Just like we see small broken station those who teach you to write, others write a good hand after a while, you can not write out how to do? Practice and write more, that’s all!

In addition, it is suggested that long-term attention should be paid to learning this => interesting programming story compilation.

Project code remember star don’t get lost, long-term more oh: this article engineering show project

Continuous learning and continuous development, I am the Lei School committee! Programming is fun, but the key is to get the technology straight. Welcome to follow, and feel free to like the collection!

Refer to the link

The actual production line in the shoe factory, the original is made like this, really let me open my eyes! The Dongguan shoe factory will set up 12 production lines in Guizhou to employ more than 2,400 people