How to use so many APIs with multiple threads?


Insert picture description here

1, setPriority sets the priority of the thread

public final void setPriority(int newPriority)

Description:
setPriority:

  1. Change the priority of this thread. First call the checkAccess method of this thread without parameters
  2. This may cause a SecurityException to be thrown. Otherwise, the priority of the thread is set to the priority of the thread group of the specified small newPriority and the maximum allowed thread.
   public static void main(String[] args) {
    
    
     Thread thread1 = new Thread(new ThreadApi_2(), "t1");
     thread1.setPriority(5);
     Thread thread2 = new Thread(new ThreadApi_2(), "t2");
     thread2.setPriority(10);
     thread1.start();
     thread2.start();
    }
    // 定义的另一个类
   class ThreadApi_2 implements Runnable {
    
    
	  @Override
	  public void run() {
    
    
	    Thread thread = Thread.currentThread();
	    System.out.println("[ 线程名称 ] —> " + thread.getName() + " [ 开始执行] -> " + thread.getState());
	    try {
    
    
	      Thread.sleep(10_000);
	    } catch (InterruptedException e) {
    
    
	      System.out.println("[ 线程名称 ] —> " + thread.getName() + " [ 线程状态] -> " + thread.getState());
	      System.out.println("sleep exception cause -> " + e.getMessage());
	    }
	  }
   }
    输出结果:
    [ 线程名称 ]> t2 [ 开始执行] -> RUNNABLE
    [ 线程名称 ]> t1 [ 开始执行] -> RUNNABLE

Conclusion:
You will find that thread2 is executed first because the thread has the highest priority.
Insert picture description here

2, isDaemon, setDaemon daemon thread API

What is a daemon thread
Description:
isDaemon: Whether the current thread is a daemon thread
setDaemon:

  1. Mark this thread as a daemon thread or a user thread. When the only thread running is the daemon thread, the Java virtual machine will exit.
  2. This method must be called before the thread starts, otherwise an IllegalThreadStateException will be issued
public static void main(String[] args) {
    
    
    Thread thread = new Thread(new ThreadApi_2());
    Thread thread1 = new Thread(new ThreadApi_2());
    // 设置当前线程为守护线程
    thread.setDaemon(true);
    thread.start();
    thread1.start();
    System.out.println(" 当前线程  -> "+ thread.getName() +" 是否是守护线程 " + thread.isDaemon());
    System.out.println(" 当前线程  -> "+ thread1.getName() +" 是否是守护线程 " + thread1.isDaemon());
    Scanner scanner = new Scanner(System.in);
    scanner.next();
    // Registers a new virtual-machine shutdown hook
    // 注册一个新的虚拟机关闭钩子
    Runtime.getRuntime().addShutdownHook(new Thread() {
    
    
      @Override
      public void run() {
    
    
        System.out.println("java 虚拟机关闭");
      }
    });
   }
   
 // 定义的另一个类
class ThreadApi_2 implements Runnable {
    
    
  @Override
  public void run() {
    
    
    Thread thread = Thread.currentThread();
    System.out.println("[ 线程名称 ] —> " + thread.getName() + " [ 开始执行] -> " + thread.getState());
    try {
    
    
      Thread.sleep(10_000);
    } catch (InterruptedException e) {
    
    
      System.out.println("[ 线程名称 ] —> " + thread.getName() + " [ 线程状态] -> " + thread.getState());
      System.out.println("sleep exception cause -> " + e.getMessage());
    }
  }
   }
   输出结果说明:
   	 当只有一个 thread 线程被设置为守护线程时此时在控制台输入一个信息回车后,java 虚拟机就会被关闭,如下:只是输入aa回车后
     输出结果:
           当前线程  -> Thread-0 是否是守护线程 true
           [ 线程名称 ]> Thread-0 [ 开始执行] -> RUNNABLE
           aa
           java 虚拟机关闭
     但是又设置了一个 thread1 为用户线程时(非守护线程)此时在控制台输入一个信息回车后,java 会等到非守护线程执行完才会关闭,此时在控制台输入了111 但是并没有立即退出JVM 而是等到了 Thread-1 线程执行完后才退出
     输出结果:
           当前线程  -> Thread-0 是否是守护线程 true
           当前线程  -> Thread-1 是否是守护线程 false
           [ 线程名称 ]> Thread-0 [ 开始执行] -> RUNNABLE
           [ 线程名称 ]> Thread-1 [ 开始执行] -> RUNNABLE
           111
           java 虚拟机关闭

in conclusion:

  1. The new thread spawned in the daemon thread is also the daemon thread
  2. The daemon thread cannot be used to access inherent resources, such as read and write operations, because it will be interrupted at any time or even in the middle of an operation
  3. Meaning of existence: When the main thread ends, the remaining child threads (daemon threads) are automatically closed. Such as: Java garbage collection thread is a typical daemon thread

3. Thread interruption

Insert picture description here
Explanation: The picture above (network interruption) is full of tears.
Interrupt: interrupt this thread, if the thread is blocked, call wait(), wait(long), or wait(long, int) method Object class, or join() , Join(long), join(long, int), sleep(long), or sleep(long, int), this class method, then its interrupted status will be cleared, and will receive an InterruptedException
isInterrupted: test this Whether the thread is hit, the interruption status of the thread is not affected by this method.
interrupted: Test whether the current thread is interrupted. This method can clear the interrupt status of the thread. In other words, if this method is called twice in a row, then the second call will return false (unless the current thread is interrupted again, after the first call has cleared its interruption status, it has been checked before the second call)

public static void main(String[] args) {
    
    
    Thread thread = new Thread(new ThreadApi_2());
    thread.start();
    thread.interrupt();
    System.out.println("thread interrupted status " + thread.isInterrupted());
}
 // 定义的另一个类
class ThreadApi_2 implements Runnable {
    
    
	@Override
	public void run() {
    
    
	  Thread thread = Thread.currentThread();
	  System.out.println("[ 线程名称 ] —> " + thread.getName() + " [ 开始执行] -> " + thread.getState());
	  try {
    
    
	    Thread.sleep(10_000);
	  } catch (InterruptedException e) {
    
    
	    System.out.println("[ 线程名称 ] —> " + thread.getName() + " [ 线程状态] -> " + thread.getState());
	    System.out.println("sleep exception cause -> " + e.getMessage());
	  }
	}
  }
  
输出结果:
     thread interrupted status true
     [ 线程名称 ]> Thread-0 [ 开始执行] -> RUNNABLE
     [ 线程名称 ]> Thread-0 [ 线程状态] -> RUNNABLE
     sleep exception cause -> sleep interrupted

Conclusion:
This code simply demonstrates that the thread simply calls interrupt() to interrupt the current thread and isInterrupted() to detect the interruption status of the current thread in the sleep state, which will be described in detail in subsequent articles (interrupted, interrupted, isInterrupted) )

4. isAlive, join, thread status

Description:
isAlive: Test whether this thread is alive. If a thread has been started and has not yet died, then the thread is a
join of isAlive : Waiting for this thread to die, that is, waiting for the current thread to finish the work in the
thread. Thread status: NEW, TERMINATED, RUNNABLE (currently three) Others will be explained in subsequent articles status

public static void main(String[] args) {
    
    
   Thread t1 = new Thread(new ThreadApi_1(), "t1");
   Thread t2 = new Thread(new ThreadApi_1(), "t2");
   t1.start();
   try {
    
    
      // isAlive 测试这个线程是否活着。 如果一个线程已经启动并且尚未死亡,那么线程是活着的
      System.out.println("[线程名称 -> " + t1.getName() + "] [线程状态 -> " + t1.getState() + "] [是否活着 -> " + t1.isAlive() + "]");
      System.out.println("[线程名称 -> " + t2.getName() + "] [线程状态 -> " + t2.getState() + "] [是否活着 -> " + t2.isAlive() + "]");
      t1.join(); // 等到 t1 线程执行完成此时 t1 线程的状态为 TERMINATED 线程 t2 一直是 NEW 状态 (一直也没启动)
      System.out.println("[线程名称 -> " +t1.getName() + " - 执行完成]");
      System.out.println("[线程名称 -> " +t1.getName() + "] [线程状态 -> " + t1.getState() + "] [是否活着 -> " + t1.isAlive() + "]");
      System.out.println("[线程名称 -> " +t2.getName() + "] [线程状态 -> " + t2.getState() + "] [是否活着 -> " + t2.isAlive() + "]");
    } catch (InterruptedException e) {
    
    
      e.printStackTrace();
    }
   t2.start();
   try {
    
    
      t2.join(); // 等到 t2 线程执行完成此时 t2 线程的状态为 TERMINATED
      System.out.println("[线程名称 -> " +t2.getName() + " - 执行完成]");
      System.out.println("[线程名称 -> " +t2.getName() + "] [线程状态 -> " + t2.getState() + "] [是否活着 -> " + t2.isAlive() + "]");
    } catch (InterruptedException e) {
    
    
      e.printStackTrace();
    }
 }
 
// 定义了另一个类
class ThreadApi_1 implements Runnable {
    
    
  @Override
  public void run() {
    
    
    Thread thread = Thread.currentThread();
    System.out.println(thread.getName() + " [ 开始执行] -> " + thread.getState());
    while (ThreadApi.COUNT <= ThreadApi.MAX_COUNT) {
    
    
      System.out.println(thread.getName() + " -> " + ThreadApi.COUNT++);
    }
  }
} 
输出结果:
	 [线程名称 -> t1] [线程状态 -> RUNNABLE] [是否活着 -> true]
	 [线程名称 -> t2] [线程状态 -> NEW] [是否活着 -> false]
	 t1 [ 开始执行] -> RUNNABLE
	 t1 -> 1
	 t1 -> 2
	 t1 -> 3
	 t1 -> 4
	 t1 -> 5
	 t1 -> 6
	 t1 -> 7
	 t1 -> 8
	 t1 -> 9
	 t1 -> 10
	 t1 -> 11
	 t1 -> 12
	 t1 -> 13
	 t1 -> 14
	 t1 -> 15
	 t1 -> 16
	 t1 -> 17
	 t1 -> 18
	 t1 -> 19
	 t1 -> 20
	 [线程名称 -> t1 - 执行完成]
	 [线程名称 -> t1] [线程状态 -> TERMINATED] [是否活着 -> false]
	 [线程名称 -> t2] [线程状态 -> NEW] [是否活着 -> false]
	 t2 [ 开始执行] -> RUNNABLE
	 [线程名称 -> t2 - 执行完成]
	 [线程名称 -> t2] [线程状态 -> TERMINATED] [是否活着 -> false]

Insert picture description here

5. Simple API such as activeCount and getName

Description:
getThreadGroup: return the thread group of the current thread
activeCount: return the estimated number of
active threads in the thread group of the current thread and its subgroups enumerate: copy each active thread in the thread group of the current thread and its subgroups to the specified
GetName in the array : return the name of this thread
getId: return the identifier of this thread
getPriority: return the priority of this thread
getState: the execution state of the current thread

new Thread(()->{
    
    
    ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
    System.out.println("activeCount -> "+ threadGroup.activeCount());
    Thread[] threads = new Thread[threadGroup.activeCount()];
    threadGroup.enumerate(threads);
    for (Thread thread : threads) {
    
    
      System.out.println("Thread name -> " + thread.getName() + ", ID -> "+
              thread.getId() + ", Priority -> " + thread.getPriority() + ", state -> " + thread.getState());
    }
    },"t1").start();
    try {
    
    
      Thread.sleep(5_100);
    } catch (InterruptedException e) {
    
    
      e.printStackTrace();
    }
    输出结果:
    	  activeCount -> 2
          Thread name -> main, ID -> 1, Priority -> 5, state -> TIMED_WAITING
          Thread name -> t1, ID -> 13, Priority -> 5, state -> RUNNABLE

Insert picture description here
Pay attention to me, I will continue to output... Looking forward to the next issue of multi-threaded learning.
Encourage with you...

Guess you like

Origin blog.csdn.net/weixin_38071259/article/details/106084787