First introduction to Java multi-threaded programming

1. Thread status

//线程的状态是一个枚举类型 Thread.State
public class ThreadState {
    
    
    public static void main(String[] args) {
    
    
        for (Thread.State state : Thread.State.values()) {
    
    
            System.out.println(state);
       }
   }
}
  • NEW: The work has been arranged, but the action has not been started yet
  • RUNNABLE: Workable. It can also be divided into currently working and about to start working.
  • BLOCKED: These all mean waiting in line for other things
  • WAITING: These all mean waiting in line for other things
  • TIMED_WAITING: These all mean waiting in line for other things
  • TERMINATED: The job is done.

2. Common properties of threads

Attributes Get method
ID getId()
name getName()
state getState()
priority getPriority()
Whether background thread isDaemon()
Is it alive? isAlive()
Whether it was interrupted isInterrupted()

3. Multi-threaded programming

There are no less than seven common methods of multi-threading implementation. We will introduce them here 继承Thread类and implement Runnable接口them. We will introduce them one by one next.

Common construction methods of Thread class

- Thread()                           // 创建线程对象
- Thread(Runnable target)            //使用 Runnable 对象创建线程对象
- Thread(String name)                //创建线程对象,并命名

1. Inherit the Thread class

First of all, we must understand that the main method in Java code can be considered the main thread.

//通过继承Thread类来实现一个线程类
class MyThread extends Thread {
    
    
    private int sum = 0;

    public  MyThread (int sum){
    
    
        this.sum = sum;
    }
    @Override
    public void run() {
    
    
        while(true){
    
    
            System.out.println("hello Thread"+sum);
        }
    }
}

public class Text1 {
    
    
    public static void main(String[] args) {
    
    
        //实例化线程类对象
        MyThread t1 = new MyThread(1);
        //通过start来启动t线程,自动执行重写的run方法
        t1.start();

        //实例化线程类对象
        MyThread t2 = new MyThread(2);
        //通过start来启动t线程,自动执行重写的run方法
        t2.start();
    }
}

Threads are executed concurrently , so the result we print is sometimes 2 and sometimes 1, as shown below:
Insert image description here

2. Implement the Runnable interface

//实现 Runnable 接口
class MyRunnable implements Runnable{
    
    
    private int sum = 0;

    public  MyRunnable (int sum){
    
    
        this.sum = sum;
    }
    @Override
    public void run() {
    
    
        while(true){
    
    
            System.out.println("hello Thread"+sum);
        }
    }
}

public class Text2 {
    
    
    public static void main(String[] args) {
    
    
        //创建 Thread 类实例, 调用 Thread 的构造方法时将 Runnable 对象作为 target 参数
        Thread t1 = new Thread(new MyRunnable(1));
        Thread t2 = new Thread(new MyRunnable(2));

        //调用t线程
        t1.start();
        t2.start();
    }
}

3. Anonymous inner class implementation

// 使用匿名类创建 Thread 子类对象
public class Text3 {
    
    
    public static void main(String[] args) {
    
    
        Thread t1 = new Thread(){
    
    
            @Override
            public void run() {
    
    
                while(true){
    
    
                    System.out.println("hello t1");
                }
            }
        };

        Thread t2 = new Thread(){
    
    
            @Override
            public void run() {
    
    
                while(true){
    
    
                    System.out.println("hello t2");
                }
            }
        };
        
        t1.start();
        t2.start();
    }
}

  • Anonymous inner classes create Runnable subclass objects in a similar way

4.lambda expression creates Runnable subclass object

//利用lambda表达式
public class Text4 {
    
    
    public static void main(String[] args) {
    
    
        Thread t1 = new Thread(()->{
    
    
            while(true){
    
    
                System.out.println("Thread t1");
            }
        });

        Thread t2 = new Thread(()->{
    
    
            while(true){
    
    
                System.out.println("Thread t2");
            }
        });

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

Note: The most commonly used method in our daily life is multi-threaded programming implemented with lambda expressions.

4. Common methods of threads

Common methods probably include:

  • Start the thread: start()
  • Waiting thread: join()
  • Get thread reference: currentThread()
  • Sleep thread: sleep(long millis)
  • Thread interruption: interrupt(), shared tag

A brief description:

1. Calling the start method will directly run the run method rewritten\implemented by the thread object we created.
2. When calling the join method, the priority of the thread object will be increased. The thread will be executed first before executing another one. Thread
3.join method can take parameters (long millis), which is intended to indicate that the thread will only wait for a certain period of time. When the time is up, the priority will be restored and executed at the same time as other threads. 4.sleep method is intended to allow the thread to
pause for a certain period of time before continuing to execute
5. .Thread interruption will be introduced in detail later, and the further use of the above methods will also be introduced in detail later.

Guess you like

Origin blog.csdn.net/m0_65038072/article/details/130656261