User thread & daemon thread & Thread group & Thread priority

If you think of a company as a process,

So you and I are user threads,

The back office is the daemon thread (ordering your water, cleaning your office, etc.),

Each project team is a thread group,

Programmer levels are priorities (senior programmers are more likely to get resources than junior programmers, but not always).

User thread & daemon thread
public static void main(String[] args)   {
        Thread t = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                    System.out.println("User thread");
                } catch(Exception e) { e.printStackTrace(); }}}); Thread tdeamon =new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(1000);
                    System.out.println("Daemon thread");
                } catch(Exception e) { e.printStackTrace(); }}});// Set thread to daemon thread!! Must be set before start or an error will be reported
        tdeamon.setDaemon(true);

        t.start();
        tdeamon.start();
    }
Copy the code

You can copy it and see, after t ends, tdeamon doesn’t run 100 times but it’s done

There are no r&d, sales, marketing positions left, so there is no need to keep logistics.

Does new Thread() default to daemon Thread or user Thread?

The new new thread defaults to the parent thread

1 Let’s look at the type of main thread
public class TestDeamon08 {
    public static void main(String[] args)   {
        System.out.println(Thread.currentThread().isDaemon() ? "Daemon thread":"User thread"); }}// Output: user thread
Copy the code
2 Let’s look at the new thread in the main thread
public static void main(String[] args)   {
        Thread t = new Thread();
        System.out.println(t.isDaemon() ? "T = daemon thread":"T = user thread");
}
// Output t= user thread
Copy the code
3 Let’s look at a thread within a thread within a main thread
public static void main(String[] args)   {
    new Thread(()->{
        Thread t2 = new Thread();
        System.out.println(t2.isDaemon() ? "T2 = daemon thread":"T2 = user thread"); }).start(); } output: t2= user threadCopy the code
We define a deamon thread and create a new thread in this thread to see if the new thread is consistent with the parent thread
public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(() -> {
        System.out.println(Thread.currentThread().isDaemon()? 
                           "Thread = daemon thread" : "Thread = user thread");
        Thread t3 = new Thread();
        System.out.println(t3.isDaemon() ? "T3 = daemon thread" : "T3 = user thread");
    });
    thread.setDaemon(true);
    thread.start();


    Thread.sleep(10000);
}

/ / output:Thread = daemon thread T3 = daemon threadCopy the code
Let’s see how new threads default daemons
// Create a thread
Thread thread = new Thread();
// The constructor's default name is thread-xxx
/ / call the init
public Thread(a) {
        init(null.null."Thread-" + nextThreadNum(), 0);
}
// the ThreadGroup is called ThreadGroup
private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null.true);
}
// Main logic
private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
    // Throw exception if thread name is null
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }
	// Set the thread name
    this.name = name;
	// Get the parent thread
    Thread parent = currentThread();
    // 
    SecurityManager security = System.getSecurityManager();
    // Initialize group if thread group is null
    // If security! = null security.getThreadGroup()
    // Get the parent thread's getThreadGroup() if security == null
    if (g == null) {
        if(security ! =null) {
            g = security.getThreadGroup();
        }
        if (g == null) { g = parent.getThreadGroup(); }}// A bunch of code...
	
    // Set the grouping
    this.group = g;
    // Set daemon to parent daemon!!
    this.daemon = parent.isDaemon();
    // Set the priority to the parent priority
    this.priority = parent.getPriority();
    
    // A bunch of code...
}
Copy the code
Thread groups

As you can see from the above code, the default grouping of threads is obtained by security, and if security is null, the parent thread grouping is used.

1. Let’s look at the thread group of the main thread
public static void main(String[] args) throws InterruptedException {
    System.out.println("Main thread group:"+ Thread.currentThread().getThreadGroup().getName()); } Thread group: mainCopy the code
2. Create a default thread group in the main thread
public static void main(String[] args)  {
    new Thread(()->{
        System.out.println("Thread Group:"+Thread.currentThread().getThreadGroup().getName());
    }).start();
}
Thread group: main

Copy the code
3. Specify a thread group
public static void main(String[] args)  {
    ThreadGroup t = new ThreadGroup("Grouping 01");
    Thread thread = new Thread(t,()->{
        System.out.println("Thread Group:"+
                           Thread.currentThread().getThreadGroup().getName());
    });
    thread.start();
}
Thread group: group 01
Copy the code
4. Create a thread in the specified thread group
public static void main(String[] args)  {
    ThreadGroup t = new ThreadGroup("Grouping 01");
    Thread thread = new Thread(t,()->{
        new Thread(()->{
            System.out.println("Thread Group:"+
                               Thread.currentThread().getThreadGroup().getName());
        }).start();
    });
    thread.start();
}
Thread group: group 01
Copy the code
5. Function of thread groups

First of all, they indicate thread ownership, so if you’re working on a thread, if it’s in the main thread group you filter it out

Periodic thread groups provide methods to batch manipulate threads:

    public static void main(String[] args)  {
        ThreadGroup g = new ThreadGroup("Grouping 01");
        Thread thread1= new Thread(g,()->{
            try {
                Thread.sleep(100000);
            } catch (Exception e) {
                System.out.println("Thread 1 terminated unexpectedly:"+e.getMessage()); }}); Thread thread2=new Thread(g,()->{
            try {
                Thread.sleep(100000);
            } catch (Exception e) {
                System.out.println("Thread 2 terminated unexpectedly:"+e.getMessage()); }}); thread1.start(); thread2.start();// Stop all threads
        // g.stop();
        // Terminates all threads
        // g.interrupt();
        // Total number of threads that are still active
        //System.out.println( g.activeCount());
        The output thread group contains thread information
        //g.list();
        // Get the maximum priority of all threads in the thread group
        //int max = g.getMaxPriority();
        // There are other readers who want to see for themselves
    }	
Copy the code
Priority

When we look at the source code in “1”, we see that the priority is the priority of the parent thread fetched by default,

So what’s the main thread priority

public static void main(String[] args) {
    int pro = Thread.currentThread().getPriority();
    System.out.println(pro);
}
// Output: 5
Copy the code

What about maximum and minimum priorities?

Thread t = new Thread();
t.setPriority(10);
// Just look at the time limit for setPriority
public final void setPriority(int newPriority) {
    ThreadGroup g;
    checkAccess();
    If MAX_PRIORITY is greater than MAX_PRIORITY or MIN_PRIORITY is less than MIN_PRIORITY, throw an exception
    // MAX_PRIORITY = MIN_PRIORITY = MIN_PRIORITY
    if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
        throw new IllegalArgumentException();
    }
    if((g = getThreadGroup()) ! =null) {
        if(newPriority > g.getMaxPriority()) { newPriority = g.getMaxPriority(); } setPriority0(priority = newPriority); }}// Get the answer
    /** * Minimum priority */
    public final static int MIN_PRIORITY = 1;

   /** * Default priority */
    public final static int NORM_PRIORITY = 5;

    /** * Maximum priority */
    public final static int MAX_PRIORITY = 10;
Copy the code

What’s the use of priorities? The above said

If the thread priority is high, the probability of obtaining CPU is high

However, it is not certain that the probability of getting the CPU before a lower priority program is just higher

Here is an example that tests the probability of priority acquiring CPU

public class ProTest02 {
    public static void main(String[] args) throws InterruptedException {
        ThreadGroup g = new ThreadGroup("Test group");
        // 4 thread priorities: 1, 3, 5, 7
        for (int i = 0; i < 4; i++) {
            String str = String.valueOf("Priority as"+ (2*i+1) +"Thread");
            new TP(str,g,2*i+1).start();
        }
        Thread.sleep(3000); g.interrupt(); }}class TP extends  Thread{
    AtomicInteger a = new AtomicInteger();
    public  TP(String name,ThreadGroup tg,int pro){
        super(tg,name);
        this.setPriority(pro);

    }
    @Override
    public void run(a) {
        while (true) {try {
                Thread.sleep(1);
                a.incrementAndGet();
            }catch (Exception e){
                System.out.println(Thread.currentThread().getName()+"Add up:"+a.get());
                break; }}}}// Output result (variable)The priority for5Thread accumulation of:2140The priority for7Thread accumulation of:2294The priority for3Thread accumulation of:431The priority for1Thread accumulation of:139
Copy the code

Welcome to our official account: