About the use of multi-threading in java (1)

Since the use of multi-threading involves a lot, it will be recorded in two articles.


Table of contents

Processes and Threads

1 Introduction

2. Advantages of multi-threading

3. Two methods to implement multi-threading

(1), inherit Thread

(2) Implement the Runnable interface


Processes and Threads

1 Introduction

A program is a collection of computer instructions, and a process is a running program, which refers to a complete process from code loading, execution to completion. Each process occupies different memory space.

A thread is a single sequential flow of control in a process, also known as a lightweight process, which is scheduled by the operating system and runs on the processor or kernel. A process has a main thread, and a process can also be composed of multiple threads. Each thread performs different tasks in parallel. These multiple threads share a memory space.


2. Advantages of multi-threading

(1) Multi-threading technology makes the program respond faster

(2) When there is currently no processing task, the CPU processing time can be given to other tasks.

(3) Tasks that require a lot of CPU processing time can regularly give up processing time to other tasks.

(4) You can stop the task at any time

(5) You can prioritize tasks by setting the priority of the task


3. Two methods to implement multi-threading

Both methods use selling tickets as an example

(1), inherit Thread

Advantages: Simple to write. If you need to access the current thread, there is no need to use the Thread.currentThread() method. You can get the current thread directly by using this.

Disadvantages: Because the thread class has inherited the Thread class, it cannot inherit other parent classes.

Specific steps:

1. Create a Thread subclass;

2. Override the methods in the Thread class;

3. Create a Thread subclass object, that is, create a thread object;

4. Call the start() method of the thread object to start the thread, and then the system will automatically call the specific implementation in the rewritten run() method.

Code example:

package Study;

public class Exp03 extends Thread{
    int ticket=6;
    //重写Thread类的run()方法
    public void run(){
        //持续卖票。一直到剩余票数为0
        while(this.ticket>=0){
            System.out.println(this.getName()+"卖票-->"+(this.ticket--));
        //对于设置线程名称,Thread类自带getName方法和setName方法。也可以使用构造方法进行设置
        }
    }
    public static void main(String[] args){
        Exp03 thread1=new Exp03();
        Exp03 thread2=new Exp03();
        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread1.start();   //线程运行
        thread2.start();
    }
}

Output results

It should be noted that in the example, 2 threads are created and allowed, the output results of multiple runs may be different. Because threads are executed through thread scheduling, many threads handle the ready state, but only one thread is actually running. Therefore, the operating system will remove a thread when it is idle and let other threads execute it, that is, thread scheduling.

 If threads are required to be executed in the order in which the program is called, it must be determined whether the previous thread has terminated before execution. This will appear in the thread synchronization discussed in the next blog post

(2) Implement the Runnable interface

Advantages: The thread class only implements the Runnable interface and can also inherit other classes. Multiple threads can share the same target object, which is very suitable for situations where multiple identical threads are processing the same resource.

Disadvantage: To obtain the current thread, you must use the Thread.currentThread() method

Specific steps

1. Define a class that implements the Runnable interface and implements the run() method;

2. Create a Runnable object as the target parameter of the Thread class to create a Thread object (the actual thread object);

3. Call the start() method to start the thread.

Code examples (2 examples, Example 2 uses the advantages of this method to modify Example 1):

Example 1:

package Study;

public class Exp03 implements Runnable{
    int ticket=6;
    //重写Thread类的run()方法
    public void run(){
        //持续卖票。一直到剩余票数为0
        while(this.ticket>=0){
            System.out.println(Thread.currentThread().getName()+"卖票-->"+(this.ticket--));
            //对于设置线程名称,Thread类自带getName方法和setName方法。也可以使用构造方法进行设置
        }
    }
    public static void main(String[] args){
        Exp03 t1=new Exp03();      //创建线程类对象
        Exp03 t2=new Exp03();
        Thread thread1=new Thread(t1);     //创建线程
        Thread thread2=new Thread(t2);
        thread1.setName("窗口1");     //给线程命名
        thread2.setName("窗口2");
        thread1.start();   //线程运行
        thread2.start();
    }
}

 Output results

Taking advantage of Runnable, modify instance 1 to enable multiple threads to process the same resource.

Example 2:

package Study;

public class Exp03 implements Runnable{
    int ticket=6;
    //重写Thread类的run()方法
    public void run(){
        //持续卖票。一直到剩余票数为0
        while(this.ticket>=0){
            System.out.println(Thread.currentThread().getName()+"卖票-->"+(this.ticket--));
            //对于设置线程名称,Thread类自带getName方法和setName方法。也可以使用构造方法进行设置
        }
    }
    public static void main(String[] args){
        Exp03 t1=new Exp03();      //创建线程类对象
        Thread thread1=new Thread(t1);     //创建线程
        Thread thread2=new Thread(t1);
        thread1.setName("窗口1");     //给线程命名
        thread2.setName("窗口2");
        thread1.start();   //线程运行
        thread2.start();
    }
}

Output result:

 It can be seen from the output results that two windows are selling 6 tickets for an object t1 at the same time, so the two windows sell a total of 6 tickets instead of the 12 tickets of instance 1.

Therefore, it is very suitable to use the Runnable interface method when using multi-threads to process shared resources.

Guess you like

Origin blog.csdn.net/weixin_47406082/article/details/123811444