Dark horse programmer Concurrent Programming Notes

1. Talk about threads and processes

1.1. Process and thread concepts

What is a process?

It can be understood that a process is a running state of programs (instructions and data) stored in static resources (disk). Generally speaking, a process is a running program.

Note: the program consists of data and instructions. To read and write these instructions, you must load the instructions into cpu and the data into memory. The process is to load instructions, manage memory and manage io

Note: memory generally refers to running memory. Because of the inaccurate concept in childhood, we often associate memory with disk storage, but the two are different.

When a program is called, it is loaded into memory from disk as a process. A program can have multiple processes (Notepad) or only one process (Netease cloud music).

Simple overview of threads

Multiple threads can be allocated in a process.

A thread is an instruction stream, which gives instructions in the instruction stream to the cpu to run.

In java, thread is the smallest scheduling unit and the smallest unit of resource allocation during process. Not active in windows, but as a container for threads.

contrast

  • The process is independent, and the thread exists in the process and is a subset of it.
  • Processes have shared resources, such as memory space, for their internal threads to share. Inter process communication is more complex
  • The process communication of the same computer is called IPC (Lnter process communication)
    Process communication between different computers needs to pass through the network and abide by common protocols, such as HTTP
  • Thread communication is relatively simple because they share memory in the process. An example is that multiple threads can access the same shared variable · threads are lighter, and the cost of thread context switching is generally lower than that of process context switching

About context switching

Simply put, it is to kill unused processes / threads to prevent them from occupying unnecessary memory.

2. Concurrency and parallelism

2.1. Concurrent

Under single core cpu, threads are actually executed serially. There is a component in the operating system called task scheduler, which distributes the cpu time slice (the minimum time slice under windows is about 15ms) to different programs. Only because the cpu switches between processes very quickly (the time slice is very short), human beings feel that it runs at the same time. It can be summarized as follows: Micro serial, macro parallel,

Generally, this method of using CPU by threads in turn is called concurrency

Popular understanding: a core calls each thread in turn.

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-fjcrk2wy-1642763425871)( https://static01.imgkr.com/temp/5d859f6d95c343e89689cdce92d8fa44.png )]

2.2. parallel

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-soe125ys-1642763425872)( https://static01.imgkr.com/temp/b5d0319a9e174b9da93062ab047b64ea.png )]

Generally speaking: multiple cores execute different threads at one time.

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-qob920rq-1642763425873)( https://static01.imgkr.com/temp/11a9e64b03c84d4abac13191dae6ad3a.png )]

2.3. Synchronous and asynchronous

Synchronous and asynchronous concepts

From the perspective of the caller, if you need to wait for the result to return to continue running, it is synchronous. If you don't need to wait, it is asynchronous

Synchronous waiting

Asynchronous wait

1) Design

Multithreading can make the execution of methods asynchronous. For example, when reading disk files, it is assumed that the reading operation takes 5 seconds. If there is no thread scheduling mechanism, the cpu can only wait 5 seconds and can't do anything.

2) Conclusion

  • For example, in a project, video file format conversion is time-consuming. At this time, open a new thread to process video conversion to avoid blocking the main thread
  • The asynchronous servlet of tomcat has a similar purpose. It allows the user thread to handle long-time operations and avoid blocking the working thread of tomcat
  • In the ui program, open the thread for other operations to avoid blocking the ui thread

3. Basic operation of java process

3.1. Create process

Method 1: directly use Thread

// The parameter of the constructor is to specify a name for the thread. It is recommended to give a name to the thread (setName() can also be used)
Thread t1 = new Thread("t1") {
 @Override
 // The task to be executed is implemented within the run method
 public void run() {
 log.debug("hello");
 }
};
t1.start();

Method 2: use Runnable to cooperate with Thread

Separate [thread] from [task] (code to be executed). Thread represents thread. Runnable task (code to be executed by thread) test2 java

// Create task object
Runnable task2 = new Runnable() {
 @Override
 public void run() {
 log.debug("hello");
 }
};
// Parameter 1 is the task object; Parameter 2 is the thread name. It is recommended to give the thread a name
Thread t2 = new Thread(task2, "t2");
t2.start();

After 1.8, lambda expression is used to simplify the writing method

// Create task object
Runnable task2 = () -> log.debug("hello");
// Parameter 1 is the task object; Parameter 2 is the thread name, which is recommended
Thread t2 = neaw Thread(task2, "t2");
t2.start();

It can also be simpler

// Parameter 1 is the task object; Parameter 2 is the thread name, which is recommended
Thread t2 = neaw Thread(() -> log.debug("hello"), "t2");
t2.start();

Shortcut key for simplifying lamba expression in idea: alt +enter

Summary

Method 1 combines threads and tasks. Method 2 separates threads and tasks. It is easier to use runnable to cooperate with advanced API s such as Thread pool. Runnable makes the task class separate from the Thread inheritance system and more flexible. By viewing the source code, you can find that method 2 is actually executed through method 1!

It should be noted that:

  • If you run the run() method of Thread directly, it is called by the main Thread

Method 3: FutureTask with Thread

FutureTask can receive parameters of Callable type, which is used to deal with the situation that there are returned results java

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // The third method to implement multithreading can return data or throw exceptions. The returned data needs to be received with get
        FutureTask futureTask = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("Multithreaded task");
                Thread.sleep(100);
                return 100;
            }
        });
        
  
        new Thread(futureTask,"My name").start();
        log.debug("Main thread");
        //{} indicates occupancy. The actual value is to buy your parameters and obtain the results. If necessary, you can get the execution result through the get method, which will block until the task returns the result.
        log.debug("{}",futureTask.get());
    }

Future is to cancel and query the execution results of specific Runnable or Callable tasks.

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

Future provides three functions:

  1. Judge whether the task is completed;
  2. Ability to interrupt tasks;
  3. Be able to obtain task execution results.

3.3 methods of viewing process threads

windows

The task manager can view processes and threads, and can also be used to kill processes

tasklist View process

taskkill Kill process

tasklist | findstr java View all java thread 

linux

ps -fe View all processes

ps -fT -p <PID> View a process( PID)All threads

kill Kill process

top Press uppercase H Toggles whether threads are displayed

top -H -p <PID> View a process( PID)All threads

ps -fe | grep java View all java process

Java

jps Command view all Java process

jstack <PID> View a Java Process( PID)All thread states for

jconsole To see a Java Operation of threads in the process (graphical interface)

jconsole remote monitoring configuration

You need to run your java class as follows

java -Djava.rmi.server.hostname=`ip address` -Dcom.sun.management.jmxremote -
Dcom.sun.management.jmxremote.port=`Connection port` -Dcom.sun.management.jmxremote.ssl=Secure connection -
Dcom.sun.management.jmxremote.authenticate=Is it certified java class

Modify the / etc/hosts file to map 127.0.0.1 to the host name

If you want to authenticate access, you also need to do the following steps

Copy jmxremote Password file

Modify jmxremote Password and jmxremote The permission of access file is 600, that is, the file owner can read and write

Fill in controlRole (user name) and R & D (password) when connecting

example:

3.2 thread operation principle

3.2.1. Virtual machine stack and stack frame

Pseudo machine stack describes the memory model of Java method execution: when each method is executed, a stack frame will be created at the same time to store local variable table, operand stack, dynamic link, method exit and other information. It is private to the thread. When multithreading is used in Java, each thread will maintain its own stack frame! Each thread can only have one active stack frame, corresponding to the method currently executing

3.2.2. Thread Context Switch

For the following reasons, the cpu no longer executes the current thread, but executes the code of another thread

  • The cpu time slice of the thread runs out (each thread executes in turn. See the previous concept of parallelism)
  • garbage collection
  • Threads with higher priority need to run
  • The thread calls sleep, yield, wait, join, park, synchronized, lock and other methods

When a Context Switch occurs, the operating system needs to save the state of the current thread and restore the state of another thread. The corresponding concept in Java is the Program Counter Register, which is used to remember the execution address of the next jvm instruction and is private to the line

3.3 common methods of thread

3.3.1 start and run

Call start

    public static void main(String[] args) {
        Thread thread = new Thread(){
          @Override
          public void run(){
              log.debug("I am a new thread running");
              FileReader.read(fileName);
          }
        };
        thread.setName("New thread");
        thread.start();
        log.debug("Main thread");
    }

Output: the program runs on thread t1, and the call of contents in the run() method is asynchronous test4 java

11:59:40.711 [main] DEBUG com.concurrent.test.Test4 - Main thread
11:59:40.711 [New thread] DEBUG com.concurrent.test.Test4 - I am a new thread running
11:59:40.732 [New thread] DEBUG com.concurrent.test.FileReader - read [test] start ...
11:59:40.735 [New thread] DEBUG com.concurrent.test.FileReader - read [test] end ... cost: 3 ms

Call run

Thread. The above code start(); Change to thread run(); The output results are as follows: the program is still running in the main thread, and the call of the contents in the run () method is still synchronous

12:03:46.711 [main] DEBUG com.concurrent.test.Test4 - I am a new thread running
12:03:46.727 [main] DEBUG com.concurrent.test.FileReader - read [test] start ...
12:03:46.729 [main] DEBUG com.concurrent.test.FileReader - read [test] end ... cost: 2 ms
12:03:46.730 [main] DEBUG com.concurrent.test.Test4 - Main thread

Summary

Calling run() directly executes run() in the main thread. If a new thread is not started, the main thread is used. Using start() starts a new thread. The code in the run() method is executed indirectly through a new thread

3.3.2 sleep and yield

sleep

  1. Calling sleep will make the current thread enter the Timed Waiting state (blocking) from Running
  2. Other threads can use the interrupt method to interrupt the sleeping thread, and the interrupted thread will throw an InterruptedException exception [Note: the interrupted thread here is the sleeping thread, not the thread in other states]
  3. After sleep, the thread may not be executed immediately (it needs to be allocated to cpu time slice)
  4. It is recommended to replace Thread's sleep() with TimeUnit's sleep() for better readability

Keywords: Java Interview

Added by hyp0r on Sun, 23 Jan 2022 17:49:54 +0200