“This is the 14th day of my participation in the First Challenge 2022.

First, use and create

For those of you who have learned threads, just remember the following three sentences to know how to use them:

  • Thread class inheritance
  • Implement the Runnnable interface
  • Implement Callable interface

But in practice, we do not need our class to inherit or implement the above several classes or interfaces, let’s look at the common way.

1.1 the Thread

Using the Thread object directly:

// Create a thread object
Thread t = new Thread() {
  public void run(a) {
  // The task to be performed}};// Start the thread
t.start();
Copy the code

1.2 a Runnable

Use Runnable with Thread: This method is a way to separate threads from tasks, where threads represent threads and Runnable represents people.

Runnable runnable = new Runnable() {
  public void run(a){
  // The task to be performed}};// Create a thread object
Thread t = new Thread( runnable );
// Start the thread
t.start();
Copy the code

The relationship between Thread and Runnable is as follows:

Thread implements the Runnable interface, and Runnable has a functional interface (I explained what a functional interface is and how to use it in java8) and only a run method.

Advantages of this approach:

  • Runnable makes it easier to work with advanced apis like thread pools
  • Using Runnable allows task classes to be more flexible without Thread inheritance

1.3 Callable

Callable is a thread use with a return value, usually in conjunction with FutureTask.

    /** * FutureTask works with callable *@param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // Create a task object
        FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call(a) {
                return 100; }});// Parameter 1 is the task object; Parameter 2 is the thread name, which is recommended
        new Thread(task, "t3").start();
        // The main thread is blocked, waiting for the result of task completion
        Integer result = task.get();

        System.out.println(result);
    }


Copy the code

The code above can be reduced using a lambda expression:

FutureTask<Integer> task = new FutureTask<>(() -> 100);
Copy the code

Second, look at threads

There are different ways to view threads on different environments, as follows:

2.1 windows

  • The task manager can be used to view the number of processes and threads, and can also be used to kill processes
  • Tasklist Displays processes
  • Taskkill Kills a process

The 2.2 Linux

  • Ps -ef View all processes
  • Ps-ft -p Displays all threads of a process (PID)
  • Kill Kill a process
  • Top toggles whether threads are displayed by pressing capital H
  • Top-h-p Displays all threads of a process (PID)

2.3 the Java command

  • The JPS command displays all Java processes
  • Jstack looks at the state of all threads for a Java process (PID)
  • Jconsole to see how threads in a Java process are doing (graphical interface)

Configure JConsole as follows:

  • You need to run your Java class as follows
Java - Djava. Rmi. Server hostname = ` IP address ` - Dcom. Sun. Management jmxremote. ` port = ` connection port - Dcom. Sun. Management. Jmxremote. If SSL = secure connection - Dcom. Sun. Management jmxremote. Authenticate = if certified Java classesCopy the code
  • Modify the /etc/hosts file to map 127.0.0.1 to the host name

To authenticate access, you need to do the following steps

  • Copy the jmxremote.password file
  • Change the permissions of the jmxremote.password and jmxremote.access files to 600, that is, file owners can read and write the files
  • When connecting, enter controlRole (username), R&D (password)

Three, the principle of thread operation

For ease of understanding, the Java JMM (Java Memory Model) is placed below, but is not the focus of this chapter:

3.1 JVM stack and stack frame

Within the Java memory model, there is an area called the Java Virtual Machine Stack. There is also the native method stack, which is used for native methods. This article uses the Java virtual machine stack as an example.

We all know that the JVM is made up of stacks, stacks, and method areas. Who is the stack (Java virtual machine stack) memory for? The virtual machine allocates stack memory for each thread that starts.

Within the virtual machine stack, each method generates a stack frame. Each stack frame represents one method call after another, the process from execution of a method to completion of execution, and the process from stack frame to stack frame.

  • Each stack consists of multiple stack frames, corresponding to the memory occupied by each method call.
  • Each thread can have only one active stack frame, corresponding to the method currently being executed.

The virtual stack throws StackOverflowError and OutOfMemoryError.

The stack frame is composed as follows:

3.2 Thread context switch

Thread Context Switch: Causes the CPU to stop executing the current Thread and Switch to executing code from another Thread.

  • The CPU slice of the thread used up. Procedure
  • The garbage collection
  • There are higher priority threads to run
  • The thread itself calls methods like sleep, yield, wait, Join, Park, synchronized, lock, and so on

When the 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 address of the next JVM instruction. Is thread private.

  • States include: program counters, information about each stack frame in the virtual machine stack, such as local variables, operand stack, return address, etc.
  • The frequent occurrence of Context switches affects performance

The next section will focus on Java’s off-the-shelf methods, states, and features.