JAVA Join + thread priority + daemon

Join

  • Join merge threads. After the execution of this thread is completed, other threads are blocked when executing other threads
  • Imagine jumping in line

package com.xiancheng.demo02;

//Test the join method and imagine jumping in line.
public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("thread  vip coming"+i);
        }
    }


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

        //Start our thread
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();



        //Main thread
        for (int i = 0; i < 1000; i++) {
            if (i == 200) {
                thread.join();//Jump in line

            }
            System.out.println("main"+i);
        }
    }
}

Thread state observation

  • Thread.State

Thread status. A thread can be in one of the following states:

  • NEW

    Threads that have not been started are in this state

  • RUNNABLE

    The thread executing in the Java virtual machine is in this state

  • BLOCKED

    Threads that are blocked waiting for a monitor lock are in this state

  • WAITING

    The thread waiting for the monitor lock is in this state

  • TIMED_WAITING

    The thread that is waiting for another thread to perform the action for the specified waiting time is in this state

  • TERMINATED

    The exited thread is in this state

A thread can be in a state at a given time. These states are virtual machine states that do not reflect the state of any operating system threads

package com.xiancheng.demo02;

//Observe the status of the test thread
public class TestState {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("//////////");
        });



        //Observation state
        Thread.State state = thread.getState();
        System.out.println(state);//NEW



        //Observe after startup
        thread.start();//Start thread
        state = thread.getState();
        System.out.println(state);//RUN


        while(state !=Thread.State.TERMINATED){//As long as the thread does not stop, it always outputs the state
            Thread.sleep(100);
            state = thread.getState();//Update thread status
            System.out.println(state);//Output thread status


        }


        thread.start();



    }

}

thread priority

  • Java provides a thread scheduler to monitor all threads that enter the ready state after startup. The thread scheduler determines which thread should be scheduled to execute according to priority

  • The priority of threads is expressed in numbers, ranging from 1 to 10

    • Thread.MIN_PRIORITY = 1;
    • Thread.MAX_PRIORITY = 10;
    • Thread.NORM_PRIORITY = 5;
  • Use the following methods to change or obtain priority

    • getPriority().setPriority(int xxx)

Priority setting is recommended before start() scheduling

package com.xiancheng.demo02;

//Test thread priority
public class TestPriority {
    public static void main(String[] args) {
        //Default priority of main thread
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();



        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);


        //Set priority first and start
        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
        t4.start();
        
    }
}


class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

Daemon thread

  • Threads are divided into user threads and daemon threads

  • The virtual machine must ensure that the user thread has completed execution

  • The virtual machine does not have to wait for the daemon thread to finish executing

  • Such as: recording operation logs in the background, monitoring memory, garbage collection and waiting

package com.xiancheng.demo02;

//Test daemon thread
//God protects you
public class TestDemo {
    public static void main(String[] args) {
        God god = new God();
        Your your = new Your();


        Thread thread = new Thread(god);
        thread.setDaemon(true);//The default is false, indicating that it is a user thread. Normal threads are user threads


        thread.start();//God daemon thread start

        new Thread(your).start();//Your user thread starts

    }

}


//lord
class God implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("God bless you");
        }
    }
}


//you
class Your implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("You live happily all your life");
        }
        System.out.println("======goodbey! world======");//Hello,world!
    }
}


You left the world and the daemon ran for a while, because it will take some time for the virtual machine to stop, and then the daemon will end.

Life is only 30000 days. You should live well.

Thread synchronization

Multiple threads operate on the same resource

  • Concurrency: the same object is operated by multiple threads at the same time

  • It shows that in life, we will encounter the problem of "many people want to use the same hospital". For example, everyone wants to eat in the canteen. The solution to sweet rice is to queue up and come one by one

  • When dealing with multithreading, multiple threads access the same object, and some threads want to modify the object. At this time, we need thread synchronization. Thread synchronization is actually a waiting mechanism. Multiple threads that need to access this object at the same time enter the object waiting pool to form a queue, wait for the previous thread to be used, and then use the next thread. (concurrent!!)

Added by pppppp on Wed, 08 Dec 2021 01:25:45 +0200