Multithreading knowledge points

  1, Basic concepts: program, process, thread

Program: a set of instructions written in a certain language to complete a specific task. It refers to a piece of static code, static object.
Process: an execution process of a program, or a running program. It is a dynamic process: it has its own process of emergence, existence and extinction—— Lifecycle (Ctrl+Shift+ESC or cmd: taskmgr open Task Manager)
 > Such as QQ in operation and MP3 player in operation
 > The program is static and the process is dynamic
 > Process is the unit of resource allocation. The system will allocate different memory areas for each process at run time
Thread: a process can be further refined into a thread, which is an execution path within a program.
 > If a process executes multiple threads in parallel at the same time, it supports multithreading
 > As a unit of scheduling and execution, each thread has an independent running stack and program counter (pc), and the overhead of thread switching is small    > Multiple threads in a process share the same memory unit / memory address space -- > they allocate objects from the same heap and can access the same variables and objects. This makes the communication between threads easier and more efficient. However, the shared system resources operated by multiple threads may bring security risks (thread synchronization).


Understanding of single core CPU and multi-core CPU:
 > Single core CPU is actually a fake multithreading, because only one thread can be executed in a time unit. example   For example, although there are multiple lanes, there is only one staff member in the toll station, and the toll can be passed only after charging, so the CPU is good   Than toll collectors. If someone doesn't want to pay, the toll collector can "hang" him (hang him until he has figured it out and has the money ready). But because the CPU time unit is very short, I can't feel it.
 > If it is multi-core, it can give better play to the efficiency of multithreading. (today's servers are multi-core)
 >  A Java application, java.exe, actually has at least three threads: main() main thread, gc() garbage collection thread, and exception handling thread. Of course, if an exception occurs, it will affect the main thread.
Parallelism and Concurrency:
 > Parallel: multiple CPU s execute multiple tasks at the same time. For example, many people do different things at the same time.
 > Concurrency: one CPU (using time slice) executes multiple tasks at the same time. For example: second kill, multiple people do the same thing.

Advantages of using multithreading
Background: Single core CPU For example, using a single thread to complete multiple tasks successively (calling multiple methods) must take less time than using multiple threads. Why do you still need multiple threads?
Advantages of multithreaded programs:
1. Improve application response. It makes more sense for the graphical interface and enhances the user experience.
2. Improve computer system CPU Utilization of
3. Improve program structure. The long and complex process is divided into multiple threads and run independently, which is conducive to understanding and implementation
modify
When do I need multithreading
>The program needs to perform two or more tasks at the same time.
> When the program needs to implement some tasks that need to wait, such as user input, file read-write operation, network operation, search, etc.
>When you need some programs running in the background.

2, Thread creation and use (key) (in API) (there are four methods in total, including two new methods after 5.0)

Multithreading creation:
Mode 1: inherit Thread class
1) Define subclass inheritance Thread Class.
2) Overridden in subclasses Thread Run method in class  --> Declare the operation performed by this thread in run()
3) establish Thread Subclass object, that is, the thread object is created.
4) Call the thread object start method: start the thread and call the run method.
         Problem 1: we can't start a thread by calling run() directly.
         Problem 2: start another thread and traverse the even number within 100. No, you can also let the thread that has started () execute. IllegalThreadStateException will be reported

  1. A simple example of using method 1 to create multithreading: traverse all even numbers within 100  

//1. Create a subclass inherited from Thread class
class MyThread extends Thread {
    //2. Override run() of Thread class
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}


public class ThreadTest {
    public static void main(String[] args) {
        //3. Create objects of subclasses of Thread class
        MyThread t1 = new MyThread();

        //4. Call start() through this object: ① start the current thread ② call run() of the current thread
        t1.start();
        //Problem 1: we can't start a thread by calling run() directly.
//        t1.run();

        //Problem 2: start another thread and traverse the even number within 100. No, you can also let the thread that has started () execute. IllegalThreadStateException will be reported
//        t1.start();
        //We need to recreate a thread object
        MyThread t2 = new MyThread();
        t2.start();


        //The following operations are still performed in the main thread.
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i + "***********main()************");
            }
        }
    }

}

2. Exercise: create two sub threads, one of which traverses an even number within 100 and the other traverses an odd number within 100

public class ThreadDemo {
    public static void main(String[] args) {
//        MyThread1 m1 = new MyThread1();
//        MyThread2 m2 = new MyThread2();
//
//        m1.start();
//        m2.start();

        //How to create an anonymous subclass of Thread class
        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if(i % 2 == 0){
                        System.out.println(Thread.currentThread().getName() + ":" + i);

                    }
                }
            }
        }.start();


        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if(i % 2 != 0){
                        System.out.println(Thread.currentThread().getName() + ":" + i);

                    }
                }
            }
        }.start();

    }
}

class MyThread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);

            }
        }

    }
}


class MyThread2 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 != 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);

            }
        }

    }
}

Common methods in Thread:
1. start(): start the current thread; Call the run() of the current thread
2. run(): you usually need to override this method in the Thread class and declare the operation to be performed by the created Thread in this method
3. currentThread(): a static method that returns the thread executing the current code
4. getName(): get the name of the current thread
5. setName(): sets the name of the current thread
6. yield(): release the execution authority of the current cpu
7. join(): join() that calls thread b in thread a. At this point, thread a enters a blocking state until thread b is fully executed, and thread a ends the blocking state.
8. stop(): obsolete. When this method is executed, the current thread is forced to end.
9. sleep(long millitime): make the current thread "sleep" for the specified millitime milliseconds. The current thread is blocked for the specified millitime milliseconds.
10. isAlive(): judge whether the current thread is alive

Thread scheduling
scheduling strategy  
 > Time slice
 > Preemptive : High priority thread preemption CPU
Java Scheduling method
 > Threads with the same priority form a first in first out queue (first in first out service) and use the time slice strategy
 > For high priority, the preemptive strategy of priority scheduling is used
thread priority
Priority level of the thread
>MAX_PRIORITY : 10
>MIN _PRIORITY : 1
>NORM_PRIORITY : 5 -- > default priority
Methods involved
>getPriority() : Gets the priority of the thread
>setPriority(int newPriority) : settings thread priority
explain
>When a thread is created, it inherits the priority of the parent thread
>Low priority only has a low probability of obtaining scheduling, and is not necessarily called after high priority threads
Thread communication: wait() / notify() / notifyAll(): defined in the Object class

1. Demonstration example: test the common methods in Thread and the priority of Thread

class HelloThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){

//                try {
//                    sleep(10);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }

                System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
            }

//            if(i % 20 == 0){
//                yield();
//            }

        }

    }

    public HelloThread(String name){
        super(name);
    }
}


public class ThreadMethodTest {
    public static void main(String[] args) {

        HelloThread h1 = new HelloThread("Thread: 1");

//        h1.setName("thread one");
        //Set the priority of threads
        h1.setPriority(Thread.MAX_PRIORITY);

        h1.start();

        //Name the main thread
        Thread.currentThread().setName("Main thread");
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
            }

//            if(i == 20){
//                try {
//                    h1.join();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }

        }

//        System.out.println(h1.isAlive());

    }
}

2. Example: create three windows to sell tickets, with a total of 100 votes. Use the method of inheriting Thread class (there is a Thread safety problem, to be solved)

class Window extends Thread{

    private static int ticket = 100;
    @Override
    public void run() {

        while (true){

            if (ticket > 0){
                System.out.println(getName() + ": Ticket No.:" + ticket);
                ticket--;
            }else{
                break;
            }
        }
    }
}

public class WindowTest {
    public static void main(String[] args) {
        Window w1 = new Window();
        Window w2 = new Window();
        Window w3 = new Window();

        w1.setName("Window 1");
        w2.setName("Window 2");
        w3.setName("Window 3");

        w1.start();
        w2.start();
        w3.start();
    }
}
Mode 2: Implementation Runnable Interface
1) Create a class that implements the Runnable interface
2) The implementation class implements the abstract method in Runnable: run()
3) Create an object that implements the class
4)   Pass this object as a parameter to the constructor of the Thread class to create an object of the Thread class
5) start() is called through the object of the Thread class

1. Demo example:

//1. Create a class that implements the Runnable interface
class MThread implements Runnable{

    //2. Implement the class to implement the abstract method in Runnable: run()
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }

        }
    }
}


public class ThreadTest1 {
    public static void main(String[] args) {
        //3. Create an object that implements the class
        MThread mThread = new MThread();
        //4. Pass this object as a parameter to the constructor of Thread class and create the object of Thread class
        Thread t1 = new Thread(mThread);
        t1.setName("Thread 1");
        //5. Call start() through the object of Thread class: ① start the Thread ② call the run() of the current Thread -- > call the run() of the target of Runnable type
        t1.start();

        //Start another thread and traverse the even number within 100
        Thread t2 = new Thread(mThread);
        t2.setName("Thread 2");
        t2.start();
    }

}

2. Example: create three windows to sell tickets, with a total of 100 tickets. Use the way to implement the Runnable interface (there is a thread security problem, to be solved.)

class Window1 implements Runnable{

    private int ticket = 100;

    @Override
    public void run() {
        while(true){
            if(ticket > 0){
                System.out.println(Thread.currentThread().getName() + ":Ticket No.:" + ticket);
                ticket--;
            }else{
                break;
            }
        }
    }
}


public class WindowTest1 {
    public static void main(String[] args) {
        Window1 w = new Window1();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName("Window 1");
        t2.setName("Window 2");
        t3.setName("Window 3");

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

}

  Compare the two ways to create threads.
During development: priority: the way to implement Runnable interface
  Reasons: 1. The implementation method does not have the limitation of single inheritance of classes. 2
             2. The implementation method is more suitable to deal with the situation that multiple threads share data.
  Contact: public class Thread implements Runnable
  The same point: both methods need to override run(), and declare the logic to be executed by the thread in run().
                At present, the two methods to start a Thread are to call start() in the Thread class.
Supplement (understanding): user thread (mian() main thread) and daemon thread (garbage collection mechanism gc()).

3, Thread life cycle

4, Thread synchronization (key and difficult points) (there are three methods to solve thread safety)

5, Thread communication

6, How to create new threads in JDK5.0

1
2
3

Tags: Python Java html

Posted on Wed, 06 Oct 2021 16:05:10 -0400 by mattee