[Big Data] Study Notes 1 Java SE Chapter 9 Multithreading 9.2 Create and start threads separately

[Big Data] Study Notes

insert image description here

1 Java SE

Chapter 9 Multithreading

9.2 Separately create and start threads

When running a Java program, there is already a thread, that is the main thread.

/**
 * @Projectname: BigDataStudy
 * @Classname: TestThread
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:43
 */

public class TestThread {
    
    

    public static void main(String[] args) {
    
    

        System.out.println("Hello thread");

    }

}

insert image description here

insert image description here

So how to create and start a thread other than the main thread?

9.2.1 Inheriting the Thread class

Java uses java.lang.Threadclasses to represent threads , and all thread objects must be instances of the Thread class or its subclasses. The role of each thread is to complete a certain task, in fact, it is to execute a piece of program flow, that is, a piece of sequentially executed code. Java uses thread execution body to represent this program flow. The steps to create and start multithreading in Java by inheriting the Thread class are as follows:

  1. Define the subclass of the Thread class, and rewrite the run() method of this class. The method body of the run() method represents the task that the thread needs to complete, so the run() method is called the thread execution body.
  2. Create an instance of the Thread subclass, that is, create a thread object
  3. Call the start() method of the thread object to start the thread

code show as below:

Custom thread class:

package com.dingjiaxiong.thread;

/**
 * @Projectname: BigDataStudy
 * @Classname: MyThread
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:47
 */

public class MyThread extends Thread {
    
    
    //定义指定线程名称的构造方法
    public MyThread(String name) {
    
    
        //调用父类的String参数的构造方法,指定线程的名称
        super(name);
    }

    /**
     * 重写run方法,完成该线程执行的逻辑
     */
    @Override
    public void run() {
    
    
        for (int i = 0; i < 10; i++) {
    
    
            System.out.println(getName() + ":正在执行!" + i);
        }
    }
}

Test class:

package com.dingjiaxiong.thread;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestMyThread
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:47
 */

public class TestMyThread {
    
    
    public static void main(String[] args) {
    
    
        //创建自定义线程对象
        MyThread mt = new MyThread("新的线程!");
        //开启新线程
        mt.start();
        //在主方法中执行for循环
        for (int i = 0; i < 10; i++) {
    
    
            System.out.println("main线程!" + i);
        }
    }
}

insert image description here

9.2.2 Implementing the Runnable interface

Java has a limitation of single inheritance. When we cannot inherit the Thread class, what should we do? The Runnable interface is provided in the core class library, we can implement the Runnable interface, rewrite the run() method, and then start and execute our thread body run() method through the object proxy of the Thread class

Proceed as follows:

  1. Define the implementation class of the Runnable interface, and rewrite the run() method of the interface. The method body of the run() method is also the thread execution body of the thread.
  2. Create an instance of the Runnable implementation class, and use this instance as the target of Thread to create a Thread object, which is the real
    thread object.
  3. Call the start() method of the thread object to start the thread.
    code show as below:

Custom thread class:

package com.dingjiaxiong.thread;

/**
 * @Projectname: BigDataStudy
 * @Classname: MyRunnable
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:48
 */

public class MyRunnable implements Runnable {
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 20; i++) {
    
    
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }
}

test class

package com.dingjiaxiong.thread;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestMyRunnable
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:49
 */

public class TestMyRunnable {
    
    
    public static void main(String[] args) {
    
    
        //创建自定义类对象  线程任务对象
        MyRunnable mr = new MyRunnable();
        //创建线程对象
        Thread t = new Thread(mr, "长江");
        t.start();
        for (int i = 0; i < 20; i++) {
    
    
            System.out.println("黄河 " + i);
        }
    }
}

operation result

insert image description here

By implementing the Runnable interface, this class has the characteristics of a multi-threaded class. The run() method is an execution target of a multithreaded program. All multi-threaded
code is inside the run method. The Thread class is actually a class that implements the Runnable interface.

When starting multi-threading, you need to first construct an object through the Thread class constructor Thread(Runnable target), and then call the start() method of the Thread object to run the multi-threaded code.

In fact, all multi-threaded code is run by running Thread's start () method. Therefore, no matter whether you inherit the Thread class or implement
the Runnable interface to achieve multi-threading, you will ultimately control the thread through the API of the Thread object. Familiarity with the API of the Thread class is the basis for multi-threaded programming.

Tips: The Runnable object is only used as the target of the Thread object, and the run() method contained in the Runnable implementation class is only used as the thread execution body.
The actual thread object is still a Thread instance, but the Thread thread is responsible for executing the run() method of its target.

9.2.3 Using anonymous inner class objects to create and start threads
    new Thread("新的线程!"){
    
    
        @Override
        public void run() {
    
    
            for (int i = 0; i < 10; i++) {
    
    
                System.out.println(getName()+":正在执行!"+i);
            }
        }
    }.start();
    new Thread(new Runnable(){
    
    
        @Override
        public void run() {
    
    
            for (int i = 0; i < 10; i++) {
    
    
                System.out.println(Thread.currentThread().getName()+":" + i);
            }
        }
    }).start();

Guess you like

Origin blog.csdn.net/weixin_44226181/article/details/130480116