Java geek

Related reading:

Java Concurrent programming (1) Knowledge map Java concurrent programming (2) Atomic Java concurrent programming (3) Visibility Java concurrent programming (4) Sequential Java concurrent programming (5) Introduction to Creating threads Java concurrent programming (6) Synchronized usage Java Concurrency programming Introduction (7) Easy to understand wait and Notify and use scenarios Java concurrency programming Introduction (8) Thread lifecycle Java concurrency programming Introduction (9) Deadlock and deadlock bit Java concurrency programming Introduction (10) lock optimization Introduction to Concurrent Programming in Java (11) Flow limiting scenarios and Spring Flow Limiting scenarios Introduction to Concurrent programming in Java (12) Producer and Consumer Patterns – Introduction to Concurrent programming in Java with code templates (13) Read/write lock and cache templates (14) CountDownLatch application scenarios Introduction to Concurrent programming in Java (18) Introduction to Concurrent programming in Java (19) Asynchronous task scheduling tool CompleteFeature Java Concurrent programming introduction (20) Common locking scenarios and locking tools


Example 1

This log is not very important and does not want to affect the core business process. It should be handled independently outside the main process. Therefore, it can be recorded by an independent thread after the request is called.

1. Each request is first queued, and the running thread retrieves data from the queue before storing it in the database.

2. Each request starts a new thread, and the data is transferred to the new thread for processing and storage.

Since thread creation and switching are expensive, it is not feasible to start a new thread for each request.

In this case, it is ok to use method 1, which can also be thought of as a thread pool with several threads running beforehand, all of which are doing the same thing.

Example 2

Pottery store opened a DIY store, each customer can make your own pottery, according to estimates, the store with the 5 sets of ceramics tool, 11 holiday overcrowded, ceramics tool is not enough, the owner went to the pottery store temporary hired two sets, after the holiday, the guest less it back again, you can see temporarily renting tao is very expensive. This example corresponds to a thread pool in code as follows:

1.Thread creation and destruction are expensive (renting and returning pottery), so you can’t create and destroy them frequently. Instead, you have several threads in advance, which are the initial threads of the Thread pool.

Thread is just a tool. It doesn’t know what the Runnable wants to do.

Thread can be reused. What each Runnable customer does is up to the Runnable. Each Runnable (customer) can do the same thing (pottery) and can do different things (pottery) without limitation.

4. If there are not enough threads, Runnable customers have to wait in line.

The corresponding class structure in Java is as follows:

1. Use the newFixedThreadPool(nThreads: INT) method to purchase pottery tools following Executors. As an ExecutorService clerk, he arranges the customers. 3. A Runnable is a guest.

Let’s look at the code to understand.

C, Show me code

I, the Customer. Java

public class Customer implements Runnable {

    / / customer name
    private final String customerName;

    // Make pottery name
    private final String porcelainName;

    public Customer(String customerName, String porcelainName) {
        this.customerName = customerName;
        this.porcelainName = porcelainName;
    }

    public void run(a) {
        makePorcelain();
    }

    // Make pottery
    private void makePorcelain(a) {
        System.out.println(Thread.currentThread().getName() + ":" + customerName + " made a " + porcelainName + "."); }}Copy the code

II, ThreadPoolTest. Java

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/ * * *@ClassName ThreadPoolTest
 * @DescriptionThread pool testing *@AuthorSonorous leaf *@Date2019/10/9 "*@Version1.0 * * * / javashizhan.com
public class ThreadPoolTest {

    public static void main(String[] args) {

        // The shop opened and bought 3 sets of pottery tools, which the shopkeeper took care of
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // The shopkeeper arranges the customers to make pottery tools
        executorService.execute(new Customer("甲"."vase"));
        executorService.execute(new Customer("乙"."bowl"));
        executorService.execute(new Customer("丙"."plate"));
        executorService.execute(new Customer("Ding"."teapot"));

        // The shopkeeper closes for the dayexecutorService.shutdown(); }}Copy the code

Output log:

Pool-1-thread-2: b made a bowl. Pool-1-thread-3: C made a plate. Pool-1-thread-1: C made a vase. D. For a teapotexit code 0
Copy the code

The thread name pool-1-thread-x indicates that there are only three threads in the thread pool.

2. Due to the shortage of pottery tools, customer D has to wait for customer B to finish the pottery before using it.

Four,

1. Both examples use thread pools. Understand what kind of thread pool the other person is talking about.

The threads in the thread pool do everything for you.

Threads in a thread pool are half packages. The thread pool provides the infrastructure (tools) to do what you need.

4. If all threads have a set set of things to do, use Executors if each thread is not sure what to do. Of course, there’s no limit to not using Executors even if the thing to do is fixed.

5. Do not use execnable to create threads for large factories because memory overflow may occur due to too much Runnable (customer) execution. However, if you use the data queue mode in example 1, memory overflow may occur as well.

The main purpose of this article is to understand the thread pool concept and/or other uses of Executors.

end.

<– Read the mark, left like!