Three ways to create Java threads

Keywords: Java

Introduction: in Java, multithreading is a very important knowledge point. It is a high-frequency knowledge point in written examination, interview, practical application and other occasions. This article is an understanding and sharing of some knowledge points in my learning process. I will use cases to show the creation of Java threads. I hope this article can be helpful to your study.

(1) Understanding of programs, processes and threads:

① Program: as the name suggests, a program is the Java code we write.

② Process: when we run the java code we write, it is a process.

③ Thread: within the process, there are multiple thread tasks running.

         In our daily surfing, we may use our own computer housekeeper, such as Lenovo computer housekeeper, Tencent computer housekeeper, etc. Open the computer manager. This is a process. In the computer manager, there are optimization acceleration and garbage cleaning... We can optimize acceleration and garbage cleaning at the same time. At this time, the thread starts.

  (Fig.1: Lenovo computer housekeeper)

         If we terminate the operation in the middle of optimizing acceleration, garbage cleaning and other operations, it means that the thread is killed.

(2) Introduction of cases

  This case: Jingdong held a Maotai rush buying activity with a limit of 10 bottles. 100 users from Beijing, Shanghai, Guangzhou and Shenzhen participated in the rush purchase. Simulate a rush purchase process to see which users grabbed Maotai.

         We will use three thread creation methods (the Callable interface is not implemented) to complete the case demonstration. We hope to use the case practice to make everyone understand the knowledge points of learning to create threads more thoroughly.

(3) Three ways to create threads

The so-called thread is simply understood as competing for resources and CPU resources. Each thread gets a certain time slice to use the CPU, and then uses resources repeatedly. At our macro level, it forms the illusion that multiple threads are running.

(1) Method 1: inherit Thread class

1. Code implementation of creating mode 1 thread:

package com.suhuiteng.Study_Thread;

/**
 * @Auther:suhuiteng
 * @Data: 2021/9/29 - 09 - 29 - 10:39
 * @Description:com.suhuiteng.Study_Thread
 * @Vesion:
 */
public class Thread01 {
    public static void main(String[] args) {
        ThreadTest01 tt1=new ThreadTest01();    //Create a specific thread
        //The above is equivalent to: Thread tt1=new ThreadTest01();
        //tt1.run();     Equivalent to an ordinary method
        tt1.start();    //You should start the thread with the start() method
    }
}

class ThreadTest01 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i <10 ; i++) {
            System.out.println("Child thread"+i);
        }
    }
}

         In order to see more clearly that our Thread is scrambling for resources, let's improve the code and let the inheritance Thread class and main () compete for resources. The code implementation is as follows:

package com.suhuiteng.Study_Thread;

/**
 * @Auther:suhuiteng
 * @Data: 2021/9/29 - 09 - 29 - 10:39
 * @Description:com.suhuiteng.Study_Thread
 * @Vesion:
 */
public class Thread01 {
    public static void main(String[] args) {
        ThreadTest01 tt1=new ThreadTest01();    //Create a specific thread
        //The above is equivalent to: Thread tt1=new ThreadTest01();
        //tt1.run();     Equivalent to an ordinary method
        tt1.start();    //You should start the thread with the start() method

        /*****main()Grab resources*******/
        for (int i = 0; i <10 ; i++) {
            System.out.println("Main thread"+i);
        }

    }
}

class ThreadTest01 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i <10 ; i++) {
            System.out.println("Child thread"+i);
        }
    }
}

          Our expected effect is that the child thread and the main thread print alternately. It is actually observed on the console that the main thread and sub thread are competing for resources:

2. Case procedure code:

package com.suhuiteng.Study_Thread;

/**
 * @Auther:suhuiteng
 * @Data: 2021/9/28 - 09 - 28 - 8:33
 * @Description:com.suhuiteng.Study_Thread
 * @Vesion:
 */
public class mythread_01 {
        public static void main(String[] args) {
            /****Create a thread to simulate the rush purchase of users in various regions*****/
            Thread th1=new BuyLiquorThread("Beijing");
            th1.start();    //Start Beijing thread
            Thread th2=new BuyLiquorThread("Shanghai");
            th2.start();    //Start Shanghai thread
            Thread th3=new BuyLiquorThread("Guangzhou");
            th3.start();    //Start Guangzhou thread
            Thread th4=new BuyLiquorThread("Shenzhen");
            th4.start();    //Start Shenzhen thread
        }
    }

/**
 * Snapping thread
 */

class BuyLiquorThread extends Thread{
        //Create constructor
        public BuyLiquorThread(String Name){
            super.setName(Name);//Sets the name of the current thread
        }

        static int LiquorNumber=10;   //Simulate the quantity of liquor, remember that with static, the four simulation areas can be shared by the number of Baijiu baijiu.

        @Override
        public void run() {
            for (int i = 1; i <=100 ; i++){
                if(LiquorNumber>0){
                    System.out.println(super.getName()+"user"+i+"Got the third"+ LiquorNumber-- +"Bottle of Maotai");
                }
            }

        }
    }

Compilation result:

(2) Mode 2: implement the Runable interface

1. Code implementation of creating mode 1 thread:

package com.suhuiteng.Study_Thread;

/**
 * @Auther:suhuiteng
 * @Data: 2021/9/29 - 09 - 29 - 10:58
 * @Description:com.suhuiteng.Study_Thread
 * @Vesion:
 */
public class Thread02 {
    public static void main(String[] args) {
        ThreadTest02 tt2=new ThreadTest02();    //Specific thread
        Thread tdd02=new Thread(tt2);    //Because the specific Thread tt2 does not have a start, we pass tt2 into the Thread to start
        tdd02.start();    //Start thread
    }
}

class ThreadTest02 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i <10 ; i++) {
            System.out.println("Child thread"+i);
        }
    }
}

         As above, in order to observe the effect of sub threads and main threads competing for resources, we improve the code (the code is not uploaded because of its length, and readers can learn and improve it by themselves). The console is observed as follows:

2. Case procedure code:

package com.suhuiteng.Study_Thread;

/**
 * @Auther:suhuiteng
 * @Data: 2021/9/28 - 09 - 28 - 8:37
 * @Description:com.suhuiteng.Study_Thread
 * @Vesion:
 */
public class mythread_02 {
    public static void main(String[] args) {
        BuyLiquorThread02 pt=new BuyLiquorThread02();
        Thread by1= new Thread(pt,"Beijing");
        by1.start();    //Start Beijing thread
        Thread by2= new Thread(pt,"Shanghai");
        by2.start();    //Start Shanghai thread
        Thread by3= new Thread(pt,"Guangzhou");
        by3.start();    //Start Guangzhou thread
        Thread by4= new Thread(pt,"Shenzhen");
        by4.start();    //Start Shenzhen thread


    }
}

class BuyLiquorThread02 implements Runnable{
    int LiquorNumber=10;    //Simulate the number of Baijiu, analog area thread is shared BuyLiquorThread02, do not add static
    @Override
    public void run() {
        for (int i = 1; i <=100 ; i++) {
            if(LiquorNumber>0){
                //Set the name to Thread.currentThread().getName()
                System.out.println(Thread.currentThread().getName()+"user"+i+"Got the third"+ LiquorNumber-- +"Bottle of Maotai");
            }
        }
    }
}

Compilation result:

(3) Method 3: implement Callable interface

        Next is the third creation method. We have learned two thread creation methods above. Why not introduce the Callable interface to create threads?

There are some limitations in inheriting Thread and implementing Runable interface:

① The Run() method can only be a Void, not a return.

② The Run() method cannot throw an exception.

         In order to have return values and throw exceptions, the implementation of Callaable interface was introduced after JDK 1.5. Let's go to the Callable interface:

  The Callable interface also has some disadvantages in creating threads, that is, creating threads is more complex than the other two methods.

The creation process is as follows:

public class mythread_03 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //The creation process is as follows:
        RadomThread rt=new RadomThread();   //Create instance
        FutureTask ft=new FutureTask(rt);   //Associating RadomThread with Thread through FutureTask method enables RadomThread to start with Start()
        Thread td=new Thread(ft);   //Create a Thread so that RadomThread and Thread are associated
        td.start(); //Start thread
        Object o=ft.get();
        System.out.println(o);

    }
}
//RadomThread is a thread that gets random numbers
class RadomThread implements Callable<Integer>{
    @Override
    public Integer call(){
        return new Random().nextInt(10);
    }
}

Create a thread that implements the Callable interface:

Instance thread name instance name = new instance thread name ();

FutureTask futuretask name = new futuretask (instance name);

Thread name = new Thread(futuretask name);

Case procedure code:

Due to the lack of thorough understanding of the knowledge system, the Callable interface is not used to realize the case analysis.

 

Conclusion: This paper mainly demonstrates the learning and sharing of the three creation methods of threads through cases. There may still be a lack of understanding of the overall logic of threads. Welcome to correct, thank you!

Posted by Sillysoft on Tue, 28 Sep 2021 21:22:12 -0700