Java multithreading Foundation

Process and multithreading

process : a Process is a running activity of a program on a data set in a computer. It is the basic unit for the system to allocate resources. In the early computer structure of Process oriented design, the Process is the basic execution entity of the program; in the contemporary computer structure of thread oriented design, the Process is the container of threads.
Program: a sequence of instructions used to let the cpu complete a specified task The java program is compiled Class file, the operating system creates a JVM virtual machine process (a JVM process is created every time the main method is executed), loads the class file in the virtual machine and runs. The process performs specific tasks by creating your new thread.
thread : thread is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operation unit in the process. A thread refers to a single sequential control flow in the process. Multiple threads can be concurrent in a process, and each thread executes different tasks in parallel.

Create multithreading

Inherit Thread class

Analyze thread information

Use the commands in jdk to analyze thread information

  1. jps+jstack.ext
  2. jmc.exe
  3. jvisualvm.exe

Implement Runnable interface


Thread. Eight construction methods of Java class

  • Thread()
    Assign a new Thread object.
  • Thread(Runnable target)
    Assign a new Thread object.
  • Thread(Runnable target, String name)
    Assign a new Thread object.
  • Thread(String name)
    Assign a new Thread object.

The constructor Thread(Runnable target) can pass in not only the Runnable interface object, but also an object of Thread class.

Thread safety issues



Add the synchronized keyword before the run() method. A thread will judge whether the run method is locked before calling the run method. If the run method is locked, it means that other threads are calling and must wait.
synchronized can lock any object and method. The locked code is called "mutually exclusive area" or "critical area".

common method

currentThread()

Which thread is the return code being called by


The constructor of run2 is called by the main thread, and the run method is called by the Thread-0 thread

The difference between the execution methods run() and start():

  1. Run method: execute the run method immediately without starting a new thread.
  2. start method: the timing of executing the run method is uncertain. start a new thread.

isAlive()

The isAlive method determines whether the current thread is alive

sleep(long millis)

Hibernate the currently executing thread within the specified time (milliseconds). The currently executing thread refers to the thread returned by this.currentThread().

sleep(long millis,int nanos)

Hibernates the currently executing thread within the specified number of milliseconds plus the specified number of nanoseconds

StackTranceElement[ ] getStackTrace()

The function is to return an array of stack trace elements representing the thread

static void dumpStack()

Outputs the stack trace information of the current thread to the standard error stream

getID()

Used to get the unique identity of the thread

Stop thread

interrupt() method

Calling the interrupt method only makes a stop mark in the current thread, not really stopping the thread

Determine whether the thread is stopped

  • public static boolean interrupted(): test whether currentThread() has been interrupted. After execution, it has the function of clearing the status flag value to false. You can also use thread Interrupted() judge, because in thread When the static static method is called in the Java class, most of them are operated on currentThread () threads.
  • public boolean this. Isinterupted(): test whether the object of the class where this keyword is located has been interrupted. It is a non static method that acts on the object calling this method. Unclear status flag.

The interrupt() method interrupts the thread

public class MyThread5 extends Thread {
    @Override
    public void run() {
        super.run();
        try{
            for (int i = 0; i <500000 ; i++) {
                if(this.isInterrupted()){
                    System.out.println("It's already stopped. I'm going to launch it!");
                    throw new InterruptedException();
                    //Or return without throwing exceptions
                }
                System.out.println("i="+(i+1));
            }
        }
        catch (InterruptedException e){
            System.out.println("get into run In method catch It's over!!");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try{
            MyThread5 myThread5 = new MyThread5();
            myThread5.start();
            Thread.sleep(2000);
            myThread5.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch!!");
            e.printStackTrace();
        }
        System.out.println("end!!!");
    }
}


sleep and interrupt
No matter the calling order, exceptions will occur whenever interrupt() and sleep() methods meet: exceptions will occur when interrupt() method is executed in sleep state; Calling the interrupt() method marks the thread with an interrupt, and an exception will occur when executing the sleep() method

Use the stop() method to stop the thread violently (not recommended)

public class MyThread6 extends Thread {
    private int i=0;
    @Override
    public void run() {
        super.run();
        try {
            while (true){
                i++;
                System.out.println("i="+i);
                Thread.sleep(1000);
            }
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread6 myThread6 = new MyThread6();
        myThread6.start();
        Thread.sleep(8000);
        myThread6.stop();
    }
}

Pause thread

In Java multithreading, you can use the suspend() method to pause the thread and the resume() method to resume the execution of the thread

suspend() and resume() methods are expired methods. The reason is that it is easy to cause the public synchronization object to be monopolized and other threads cannot access the results of the public synchronization object. Therefore, to suspend and resume threads, you can use wait(), notify() or notifyAll() methods
System.out.println is also a synchronization method

yield method

The yield method is used to give up the current cpu resources and let other tasks occupy the cpu execution time. The time of giving up is uncertain. It may just give up and get the cpu time slice immediately

thread priority

In Java, the priority of a thread is divided into 10 levels from 1 to 10. If the priority of a thread is less than 1 or greater than 10, the JDK throws an exception throw new illegalargumentexception()

  1. Inheritance property of thread priority
    In Java, the priority of threads is inherited. For example, if thread A starts thread B, the priority of thread B is the same as that of thread A
public class MyThread10 extends Thread {
    @Override
    public void run() {
        super.run();
        System.out.println("MyThread10 run priority="+this.getPriority());
    }
}
public class MyThread9 extends Thread {
    @Override
    public void run() {
        super.run();
        System.out.println("MyThread9 run priority="+this.getPriority());
        MyThread10 myThread10 = new MyThread10();
        myThread10.start();
    }

    public static void main(String[] args) {
        System.out.println("main thread begin priority="+Thread.currentThread().getPriority());
        //Thread.currentThread().setPriority(6);
        System.out.println("main thread end priority="+Thread.currentThread().getPriority());
        MyThread9 myThread9 = new MyThread9();
        myThread9.start();
    }
}


Remove comments

2. Priority rule
Most high priority threads are always executed first, but it does not mean that all high priority threads are executed first. The CPU tries to give execution resources to threads with higher priority. The priority and execution order of threads are uncertain and random

Daemon thread

There are two kinds of threads in Java, one is user thread, the other is guard thread
Daemon thread is a special thread. When there is no user thread in the process, the daemon thread is automatically destroyed. A typical daemon thread is a garbage collection thread
Only when the last user thread ends, the daemon thread ends with the JVM. The role of the daemon thread is to provide services for other running threads.

public class MyThread11 extends Thread {
    private int i=0;

    @Override
    public void run() {
        super.run();
        try{
            while(true){
                i++;
                System.out.println("i="+(i+1));
                Thread.sleep(1000);
            }
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try{
            MyThread11 myThread11 = new MyThread11();
            myThread11.setDaemon(true);
            myThread11.start();
            Thread.sleep(5000);
            System.out.println("main End, the daemon thread ends!");
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}

Keywords: Java Back-end Multithreading

Added by Rigo on Tue, 21 Dec 2021 18:59:43 +0200