Daemon Thread in Java language

Keep creating and accelerate growth! This is my 19th day participating in the "Nuggets Daily New Plan·October Update Challenge", click to view event details

daemon thread

There are two types of threads in the Java language: user threads and daemon threads. In layman's terms, any daemon thread is the "big housekeeper" of all threads in the entire JVM; as long as there is any non-daemon thread in the current Java virtual machine that has not ended, their daemon threads cannot end and must continue to work; Only when the last non-daemon thread ends, the daemon thread ends its work with the Java virtual machine.

  • Its role is to provide services for the operation of other threads, like a protector , ensuring the smooth operation of other threads

Set user thread as daemon thread

The way we set the user thread as a daemon thread is the setDaemon(true) method of the Thread class. Suppose we create a thread t, and then we set it as a daemon thread. At this time we should pay attention to: 1. The daemon thread should never access system resources (such as databases, files, etc.), because it will even An interruption occurred while some operation was in progress. 2. Threads defined by the daemon thread during runtime and created by the daemon thread are naturally daemon threads. 3. t.setDaemon(true) must be called before t.start(), otherwise an IllegalThreadStateException will occur. The reason is that you cannot set a running regular thread as a daemon thread.

  • code example

    SubThead class:

```java public class SubThread extends Thread{ int u1,v1; int result=0; //Construction method public SubThread(String name){ super(name); //Randomly generate an integer within 0~100 u1=(int )(Math.random() 100); v1=(int)(Math.random() 100);

}

    @Override
    public void run() {
        //如果没有最大公约数,就进行计算
        if (result==0){
            result=this.getMaxCommonDivisor();
            System.out.println ("运行····"+this);
            while (true){
                Thread.yield ();  //暂停当前线程,执行其他线程
            }
        }
    }
    //得到最大公约数
    public int getMaxCommonDivisor() {
        int u=u1,v=v1,r=u;
        while (r!=0){
            u=v;
            v=r;
            r=u%v;
        }
    return v;
    }

    @Override
    public String toString() {
        String msg;
        msg="threadName:"+this.getName ()+", ahead(优先级):"+getPriority ();
        String msg1=this.isDaemon ()?",守护线程:" :"用户线程";
        msg=msg+msg1+".["+u1+","+v1+"的最大公约数是"+result+"]";
        return msg;
    }
}

``` Note: public int getMaxCommonDivisor(): This method is to get the greatest common divisor of u1 and v1

DaemonThread class

```java import com.alibaba.druid.support.json.JSONUtils;

import java.sql.SQLOutput;

public class DaemonThread extends Thread{ public DaemonThread(String name){ super(name); } public void print(){ String msg; msg="Thread:"+getName ()+";Priority"+getPriority ()+" , is the daemon thread"+isDaemon (); System.out.println (msg); return; }

@Override
public String toString() {
    String msg;
    msg = "threadName:" + this.getName () + ", ahead(优先级):" + getPriority ();
    String msg1 = this.isDaemon () ? ",守护线程:" : "用户线程";
    msg="线程名:"+this.getName ()+",优先级"+this.getPriority ()+msg1;
    return msg;
}

@Override
public void run() {
    int i;
    System.out.println ("运行---"+this);
    //定义子线程
    SubThred subThred[]=new SubThred[5];
    //创建子线程
    for (int i = 0; i < 5; i++) {
        subThred[i]=new SubThread("子线程:"+i);
    }
    for (int i = 0; i < 5; i++) {
        subThred[i].start();//启动子线程
    }
}

} ```

DaemonTest class

```java

import java.util.concurrent.TimeUnit;

public class DaemonTest{ //Output thread information public static void print(Thread t) { String msg; String msg1 = this.isDaemon () ? ", Daemon thread:" : "User thread"; msg="Thread name: "+ this.getName ()+",priority"+this.getPriority ()+msg1; System.out.println (msg); return ; }

public static void main(String[] args) throws InterruptedException{
    //得到当前主线程
    Thread t = Thread.currentThread ();
    //输出当前主线程
    print ( t );
    DaemonThread daemonThread =new DaemonThread("守护线程A" );
    daemonThread(true);//将线程设为守护线程
    daemonThread.start();
    //主线程睡眠
    TimeUnit.SECONDS.sleep ( 5 );
    //输出当前主线程
    print ( t );
}

} ``` Note: During the process of running the main method of the DaemonTest class, the main thread obtains the system resources and is in a running state, then creates thread A, then sets A as a daemon thread and starts thread A. Thread A is created The daemon threads A1, A2, A3, and A4 are installed. Then, the main thread sleeps for 5 seconds. At this time, several sub-threads created by thread A are awakened and enter the running state respectively. During the running process of the sub-thread, the greatest common divisor of two random numbers is randomly generated, and then enters the pause state. After the main thread sleeps, it obtains system resources again. The code execution ends, the life of the main thread ends, and the child thread is also recycled by the system...

Guess you like

Origin blog.csdn.net/y943711797/article/details/132972186