Multithreading (3) Thread class and common methods

First, several properties of the Thread class

insert image description here

⭐① The ID is the unique identifier of the thread, and different threads will not be repeated.
② The name is used by various debugging tools.
③ The status indicates the current situation of the thread. We will further explain below.
⭐④ High priority Threads are theoretically easier to be scheduled to
⑤About daemon threads (background threads), you need to remember one thing: JVM will end running after all non-background threads of a process are finished.
⑥Whether it is alive , that is, a simple understanding, whether the run method has finished running or not.
The thread interruption problem

property: state - getState()

  Thread thread = new Thread(() ->{
    
    
            System.out.println("当前线程的状态1" + Thread.currentThread().getState());
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        });
        System.out.println("当前线程的状态2" + thread.getState());
        thread.start();

Attributes: ID and Name – getId() and getName()

/**
 * 线程属性
 * ID和名称 ;ID一定是不同的,是动态分配的
 * 线程名称手动设置
 */
public class ThreadDemo11 {
    
    
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                Thread t = Thread.currentThread();
                System.out.println("线程ID" + t.getId());
                System.out.println("线程名称" + t.getName() );
            }
        });
        thread.start();
    }
}

attribute: priority - getPriority()

/**
 * 获取优先级
 */
public class ThreadByPriority {
    
    
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                // 得到当前线程,并打印线程的优先级
                Thread thread1 = Thread.currentThread();
                System.out.println("线程优先级1:" + thread1.getPriority());
            }
        });
        System.out.println("线程优先级2:" + thread.getPriority());
        thread.start();
    }
}

Attribute: whether to daemon thread-isDaemon()

 //在主线程创建子线程
        Thread t = new Thread(()->{
    
    
            Thread t1 = Thread.currentThread();
            System.out.println(t1.getName() + "是否守护线程" + t1.isDaemon());
            // 创建子线程
            Thread tt1 = new Thread(() -> {
    
    
                Thread cThread2 = Thread.currentThread();
                System.out.println(cThread2.getName() + "——是否守护线程:" + cThread2.isDaemon());
            }, "子线程的子线程1");
            tt1.start();
        },"子线程1");

Attribute: alive or not - isAlive()

/**
 * 线程是否存活 isAlive() -while循环
 */
public class DaemonThreadAlive {
    
    
    public static void main(String[] args) {
    
    
        Thread t = new Thread(() ->{
    
    
          for(int i=0;i < 10;i++){
    
    
              try {
    
    
                  Thread.sleep(5000);
              } catch (InterruptedException e) {
    
    
                  e.printStackTrace();
              }
          }
            System.out.println("执行完了");
        });
        t.start();
        //判断是否存活
        while(t.isAlive()){
    
    
        }
        System.out.println("确认执行完了");
    }
}

Second, start a thread - start()

The thread object can be considered to have called Li Si and Wang Wu over.
And calling the start() method is to shout: "Go!", and the thread can truly execute independently.

  Thread thread = new Thread(()->{
    
    
      //业务代码
    Thread thread3 = Thread.currentThread();
    System.out.println("名称" + thread3.getName());
  });
  //启动线程
  thread.start();

Third, the method of interrupting the thread

There are currently two common methods:

1. Communicate through shared markup

//declare a custom identifier
private volatile static boolean flag = false;

/**
 * 自定义标识符终止线程
 */
public class InterruptThread1 {
    
    
    //声明一个自定义标识符
    private volatile static boolean flag = false;
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(() -> {
    
    
            while(!flag){
    
    
                System.out.println("正在转账");
                try {
    
    
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
            System.out.println("差点误了大事");
        });
        thread.start();
        System.out.println("执行结束");
    }
}

Whether the flag is cleared

Whether the flag is cleared is similar to a switch.
Thread.isInterrupted() is equivalent to pressing the switch, and the switch automatically pops up. This is called "clearing the flag"
Thread.currentThread().isInterrupted() is equivalent to pressing the switch After that, the switch will not bounce, this is called **"not clearing the flag".**

2. Call the interrupt() method to notify

insert image description here

// Terminate the thread
thread.interrupt();
System.out.println("Terminate transaction");

   thread.start();
   Thread.sleep(1000);

     //终止线程
   thread.interrupt();
   System.out.println("终止交易");
   System.out.println("终止标志位3" + Thread.currentThread().isInterrupted());

3. The difference between interrupted and isInterrupted

①interrupted is a static method, a global method that can be used by all programs, isInterrupted is a method of an instance
②interrupted will reset the identifier after use isInterrupted will not reset

Please see the detailed analysis

Link : https://blog.csdn.net/qq_55660421/article/details/123662613 .

Fourth, wait for a thread-join()

Sometimes, we need to wait for a thread to complete its work before we can proceed to our next work. For example, Li Si only decides whether to work after Zhang San's work is successful. At this time, we need a method to explicitly wait for the end of the thread
insert image description here

public class ThreadByJoin {
    
    
    public static void main(String[] args) throws InterruptedException{
    
    
        Thread t1 = new Thread(() -> {
    
    
            // 1.张三开始上班
            System.out.println("1.张三开始上班");
            // 2.张三正在上班
            try {
    
    
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            // 3.张三下班
            System.out.println("3.张三下班");
        });
        // 启动程序
        t1.start();
//        while (t1.isAlive()) {
    
    
//        }
        // 等待线程 t1 执行完之后,再执行后面的代码
        t1.join();
        Thread t2 = new Thread(() -> {
    
    
            // 1.李四开始上班
            System.out.println("1.李四开始上班");
            // 2.李四正在上班
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            // 3.李四下班
            System.out.println("3.李四下班");
        });
        t2.start();
    }
}

Five, sleep the current thread

There are two implementations of sleeping threads:

Use sleep to sleep

We are also familiar with a set of methods. One thing to remember is that because the scheduling of threads is uncontrollable, this method can only ensure that the actual sleep time is greater than or equal to the sleep time set by the parameters.

insert image description here

/**
 * 休眠线程
 */
public class ThreadSleep {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        Thread t = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                try {
    
    
                    Thread.sleep(10*1000);
                } catch (InterruptedException e) {
    
    
                    System.out.println("我接收到了中止执行的通知");
//                e.printStackTrace();
                }
            }
        });
        t.start();
        //休眠线程
        Thread.sleep(1000);
        System.out.println("终止子线程 thread");
        t.interrupt();//终止线程
    }
}

Sleep with TimeUnit

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 休眠线程
 */
public class ThreadTimeUtil {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        System.out.println("主线程开始执行了:" + LocalDateTime.now());
        TimeUnit.SECONDS.sleep(3); // 休眠 3s
        System.out.println("主线程又开始执行了:" + LocalDateTime.now());
    }
}

Six, get a reference to the current thread

insert image description here

public class ThreadDemo {
    
    
  public static void main(String[] args) {
    
    
     Thread thread = Thread.currentThread();
     System.out.println(thread.getName());
  }
}

Guess you like

Origin blog.csdn.net/qq_55660421/article/details/123707687