Overview of multithreading, creating threads: Inheriting Thread class and implementing Runnable interface

Posted by badzv on Sun, 20 Feb 2022 04:59:23 +0100

1, Overview

1. Process:

The running program is an independent unit for the system to allocate and call resources. Each process has its own memory space and resources.

2. Thread:

It is a single sequential control flow of a process, or a separate execution path
If a process has only one execution path, it is called single thread
If a process has multiple execution paths, it is called multithreading
Threads are included in the process.

3. Three key words:

(1) serial refers to that all tasks in a program are executed in sequence. When the previous task has not been processed, the next task will not be processed
For example: there is only one barber in a barber shop. Many people go to have their hair cut. First wait for the person in front of them to have their hair cut, and then it's their turn to the person behind them.
(2) parallelism refers to assigning tasks to different processors for processing, and then serial processing is carried out in each processor.
For example: there are many windows in the railway station. Multiple windows sell tickets at the same time, but for one window, one person sells tickets one by one
(3) concurrency is essentially a phenomenon. Concurrency needs the support of the processor. For example, when a task is delivered, the operating system can call and process other tasks, whether serial or parallel
All need the support of the operating system for concurrency. Assuming that drinking water is a task, the conductor of each railway station can drink water while selling tickets, which supports concurrency.

4. jvm starts with multithreading, main thread (main thread) and garbage collection thread

2, Multithreading implementation scheme

1. The first way to create a Thread: inherit the Thread class

(1) steps

Create a custom class to inherit the Thread class: suppose the created class is called MyThread1
This class overrides the run method in the Thread class
When the thread starts, the code logic executed is only the code logic of the run() method
Create a thread object based on this class: MyThread1 myThread1 = new MyThread1(); In order to realize multithreading, at least two or more thread objects should be created

Start thread: if the run() method is called, it is no different from the implementation of ordinary methods. You need to use the start() method to implement it

The difference between calling start() and calling run()
The run() method only encapsulates the code executed by the thread, but there is no difference between calling run() directly and calling ordinary methods
To call the start() method, first start a thread separately, and then the JVM calls the run() method in the thread class

 

(2) Realize

class Student extends Thread {
    @Override
    public void run() {
        for(int i=0;i<200;i++){
            System.out.println(i);
        }
    }
}

public class Test1 {
    public static void main(String[] args) {
       Student s1=new Student();
       Student s2=new Student();

       s1.start();
       s2.start();

    }
}

 

(3) Method in Thread class: public final String getName() returns the name of this Thread

public final void setName(String name) changes the name of this thread to be equal to the parameter name.

public static Thread currentThread() returns a reference to the currently executing thread object, and adds getName() to get the name of the thread.

class Student extends Thread {
    public Student() {
    }

    public Student(String name) {//Name the thread through the construction method
        super(name);
    }

    @Override
    public void run() {
        for(int i=0;i<200;i++){
            System.out.println(getName()+":"+i);//You can call the methods of the parent class directly
        }
    }
}

public class Test1 {
    public static void main(String[] args) {
       Student s1=new Student();
       Student s2=new Student();

       s1.setName("CuoJue ");
       s2.setName("Zhang Jie");


       s1.start();
       s2.start();

    }
}
 public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
    }
result
main

(4) Thread priority

The default priority for threads is 5
The thread priority range is 1-10
High thread priority may be obtained first than low thread priority. High thread priority only means that the probability of obtaining CPU time slice will be higher, but it is not always obtained

Method to get thread priority:
public final int getPriority() returns the priority of this thread.
How to set thread priority:
public final void setPriority(int newPriority) changes the priority of this thread.

Student s1 = new Student();
        Student s2 = new Student();

        s1.setPriority(1);
        s2.setPriority(4);
        
        System.out.println(s1.getPriority());
        System.out.println(s2.getPriority());
The results are 1 and 4

(5) Threads have two scheduling models:

Time sharing scheduling model} all threads use the right of CPU in turn, and evenly allocate the time slice of CPU occupied by each thread

The preemptive scheduling model gives priority to the threads with high priority to use the CPU. If the threads have the same priority, one will be selected randomly. The threads with high priority get relatively more CPU time slices.

So to sum up, Java uses a preemptive scheduling model.

(6) Thread control

Thread sleep public static void sleep (long millisecond): added to the object class, the thread needs to try every millisecond of execution catch..

public class Student extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            System.out.println(getName() + ":" + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Thread join: public final void join(): the call of join must be after start, and try catch..
The purpose of thread object calling join is to let the current thread execute first, and then other threads execute. In other words, other threads wait for the thread calling join to execute.

Student s1=new Student();
       Student s2=new Student();

       s1.setName("Xiao Qing Zhang");
       s2.setName("Daqing Zhang");

       s1.start();
        try {
            s1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        s2.start();
join join After, s1 It will not run until the operation is completed s2 thread 

Comity thread: public static void yield(): added to the run() method of the object class, which is used as the sleep() method
Pause the currently executing thread object and execute other threads. Its function is to make multiple threads look more harmonious when running. However, it does not guarantee that multiple threads can run once.

Background thread: (daemon thread) public final void setDaemon(boolean on)

There are two kinds of threads in Java: user thread and daemon thread

User thread: before learning multithreading, the running threads are user threads

Daemon thread: the so-called daemon thread refers to a general service thread provided in the background when the program is running. For example, the garbage collection thread is a daemon thread
And this thread does not necessarily exist, so conversely, as long as the program has a daemon thread, the program will not terminate.

be careful:
1. The daemon thread must be set before starting
2. When the running program has only one thread and this thread is a guard thread, the Java virtual machine exits (the program stops)

Student s1=new Student();
       Student s2=new Student();

       s1.setName("Xiao Qing Zhang");
       s2.setName("Daqing Zhang");
       s2.setDaemon(true);

       s1.start();
       s2.start();
At first s1 and s2 Is preemptive operation, when s1 After running, only the daemon thread is left in the thread s2 After, jvm Will stop running,
therefore s2 stay s1 After running, it stopped after running for a while and did not finish running

Interrupt thread: public void interrupt():

class MyStopThread extends Thread {
    @Override
    public void run() {
        System.out.println("Start execution time:" + new Date());
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("End time:" + new Date());
    }
}
public class ThreadStopDemo {
    public static void main(String[] args) {
        MyStopThread t1 = new MyStopThread();
        t1.setName("floret");
        t1.start();
        t1.interrupt(); //When sleep is interrupted, the code behind the run method continues to execute. After execution, an exception is thrown
    }
}
result
 Start execution time: Sun Feb 20 10:21:33 CST 2022
 End time: Sun Feb 20 10:21:33 CST 2022
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.shujia.yh.pratice.MyStopThread.run(Test1.java:10)

(7) Summary

2. Implementation scheme 2 of multithreading: implement Runnable interface

(1) Steps
Customize a class to implement the Runnable interface
Implement the run() method
Create custom class object
Create a Thread object and pass the custom object as a parameter to the construction method

(2) Realize

class Ra implements Runnable {
    @Override
    public void run() {
        for(int i=0;i<200;i++){
            //Since there is no getName() method in the Runnable interface, the name of the thread object cannot be obtained here
            //Indirectly, we can get the object of the current Thread first, and then call the getName() method in the Thread class
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }
}
public class Test1 {
    public static void main(String[] args) {
        Ra r1=new Ra();

        Thread t1=new Thread(r1);
        Thread t2=new Thread(r1);

        t1.setName("Xiao Qing Zhang");
        t2.setName("Daqing Zhang");

        t1.start();
        t2.start();
    }
}

Topics: C# linq p2p