Detailed explanation of basic usage of Thread class

The role of the Thread class

Thread is the core class for Java to operate multithreading .

thread creation

There are many ways to create threads in Java! ! !

Inherit Thread, rewrite run

//继承Thread类并重写run方法创建一个线程
class Thread01 extends Thread{
    
    
    @Override
    public void run() {
    
    
        System.out.println("hello,thread");
    }
}
public class ThreadDemo {
    
    
    public static void main(String[] args) {
    
    
        //实例化一个线程对象
        Thread01 t=new Thread01();
        //真正去申请系统线程,参与CPU调度
        t.start();
    }
}

Implement Runnable, rewrite run

//通过继承Runnable接口并实现run方法
class MyRunnable implements Runnable{
    
    
    @Override
    public void run() {
    
    
        System.out.println("hello,thread");
    }
}
public class ThreadDemo {
    
    
    public static void main(String[] args) {
    
    
         //实例化Runnable对象
        MyRunnable runnable=new MyRunnable();
        //实例化线程对象并绑定任务
        Thread t=new Thread(runnable);
        t.start();
    }
}

Inherit Thread, rewrite run, use anonymous inner class

 //通过Thread匿名内部类的方法创建一个线程
public static void main(String[] args) {
    
    
       Thread t=new Thread(){
    
    
            //指定线程任务
            @Override
            public void run() {
    
    
                System.out.println(Thread.currentThread().getName());
            }
        };
        t.start();
}

Implement Runnable, rewrite run, use anonymous inner class

//通过Runnable匿名内部类创建一个线程
   public static void main(String[] args) {
    
    
      Thread t=new Thread(new Runnable() {
    
    
          //指定线程的任务
          @Override
          public void run() {
    
    
              System.out.println(Thread.currentThread().getName());
          }
      });
      t.start();
   }

Using a lambda expression (most recommended)

//通过Lambda表达式的方式创建一个线程
public static void main(String[] args) {
    
    
    Thread t=new Thread(()->{
    
    
        System.out.println("Hi");
    });
    t.start();
}

The above methods are just different in syntax rules, and are essentially the same method, and the threads created are not different.

Interview question 1: Please explain the difference between run and start in the Thread class
Answer:
The functions are different:
a. The function of the run method is to describe the specific tasks to be performed by the thread;
the function of the b. start method is to actually create a thread in the operating system kernel and let the new thread call the run method.
The running results are different:
a. The run method is an ordinary method in a class. Active calling is the same as calling ordinary methods, and it will be executed sequentially once.
b. After the start method is called, the start method will call the Java native method (encapsulating the call to the bottom layer of the system) to actually start the thread, and execute the code in the run method. After the run method is executed, the thread enters the destruction stage.

thread interrupt

The meaning of interruption does not mean to stop the thread immediately, but to notify the thread that it should stop . Whether it really stops depends on the specific code writing method of the thread here.

1. Use the flag bit to control whether the thread should stop

    public static boolean flag=true;
    public static void main(String[] args) throws InterruptedException {
    
    

        Thread t=new Thread(()->{
    
    
            while (flag){
    
    
                System.out.println("hello Thread");
                try {
    
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
        });
        t.start();
        Thread.sleep(3000);
        //在主线程里就可以随时通过flag变量的取值,来操作t线程是否结束
        flag=false;

    }
  • This method of custom variables cannot respond in time, especially when the sleep sleep time is relatively long.
  • The reason why this code can modify the flag and end the t thread depends entirely on the code inside the t thread.
  • The loop is controlled by the flag in the code. So here is just to tell this thread to end, whether this thread will end and when it will end depends on the internal code of the t thread.

2. Use the flag bit that comes with Thread to control whether the thread should stop

public static void main(String[] args) throws InterruptedException {
    
    

    Thread t=new Thread(()->{
    
    
        while (!Thread.currentThread().isInterrupted()){
    
    
            System.out.println("hello Thread");
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    });
    t.start();
    Thread.sleep(3000);
    t.interrupt();
}

Thread.currentThread(): This is a static method of the Thread class. Through this method, the current thread can be obtained. Which thread calls this method will get the object reference of which thread, similar to this.
isInterrupted(): Determine whether the thread is terminated, true means terminated, false means not terminated.
t.interrupt(): In the above code, the main thread calls t.interrupt(), which is equivalent to the main thread notifying the t thread to terminate.

insert image description here

Here interrupt will do two things:
1. Set the flag bit (boolean) inside the thread to true.
2. If the thread is sleeping, it will trigger an exception and wake up the sleep.
Note:
When waking up sleep, the flag bit just set will be set back to false. (The flag bit is cleared)
This causes the above code to continue to execute after the sleep exception is caught! !
Execution results of the above code:
insert image description here
Question 1: Why does sleep clear the flag?
After waking up sleep, whether the thread should be terminated, whether to terminate immediately or later, depends on the internal code of the thread.

thread wait

Thread waiting means that a thread suspends its own operation during execution and waits for other threads to complete certain operations before continuing to execute. Simply put, it is to control the execution order of multiple threads.
There are many ways to implement thread waiting, the most common way is to use the thread's join() method. When a thread calls the join() method of another thread, it is blocked until the called thread finishes executing and exits.

insert image description here
The result of executing the above code:
insert image description here

Guess you like

Origin blog.csdn.net/m0_63904107/article/details/130982938