SoFunction
Updated on 2025-03-08

Detailed explanation of common operations in Java threads

Common operations of threads

Set the thread name: setName()

Get the thread name: getName()

Thread unique Id: getId()

// Custom thread nameString threadName = "threadName";
//Construction methodThread thread = new Thread(() -> {
    ("Thread name=" + ().getName());
},threadName);
// Set method// (threadName);
("Thread uniqueId=" + ());

Thread start: start()

Determine whether the thread survives: isAlive()

// Thread starts();
("Is it a survival thread?=" + ());

Thread method: run() /call()

A method that will be called after the thread is started. What a thread wants to do is write it in the run/call method. There is no need to call it directly. After the thread starts, it will call run() /call() itself. If the program does not start the thread and directly calls run/call, it does not belong to multi-threaded programming, but is the same as the current thread directly calls ordinary methods.

Get the current thread object: currentThread()

Operate the non-static method of the current thread, you must first get the thread object.

// Get the current thread objectThread currentThread = ();
// Do some operations on the current thread(());
try {
    // Sleep static method does not require    (1000);
} catch (InterruptedException e) {
    ();
}

For the operation of thread state control (life cycle) you can refer to the previous article.

Daemon thread (background thread)

The guardian of ordinary threads (user threads), the task of the daemon thread is to provide services to other threads. If there is no user thread in the process, then the daemon thread has no meaning and the JVM will end. Typical daemon threads include JVM garbage collection threads, and the startup of the operating system will also start daemon threads of various modules.

Set the thread to the daemon thread: setDaeman()

Note: This method must be called before the start() method

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        ("Thread name="+().getName());
        try {
            (1000);
        } catch (InterruptedException e) {
            ();
        }
        // This sentence will not be printed out, because the main thread (the only ordinary thread at present) has ended after waiting for 1 second        ("The status of the daemon thread=" + ().getState());
    });
    // Daemon thread    (true);
    // Thread starts    ();
    ("Is it a daemon thread?=" + ());
}

Thread serialization

The thread that executes the join() method entersWaiting for Wake-up (WAITING),untilThe thread that calls the methodAfter the end, it will change from waiting to wake up to run (RUNNABLE). The join() method is a method in the Thread class. The underlying layer is to use the wait() method to implement thread waiting, and it will only be done when the thread isAlive() is false.

Implement serialization of threads: One thread calls join() of another thread object to implement serialization of threads.

For example: a good dish

public class DemoCooking {
    
    public static void main(String[] args) {
        Thread mainThread = ();
        // 1. Buy vegetables        Thread buyThread = new Thread(new CookingThread(mainThread,"Buy groceries"),"buyThread");
        // 2. Wash vegetables        Thread washThread = new Thread(new CookingThread(buyThread,"Wash vegetables"),"washThread");
        // 3. Cut vegetables        Thread cutThread = new Thread(new CookingThread(washThread,"Cut vegetables"),"cutThread");
        // 4. Frying dishes        Thread scrambleThread = new Thread(new CookingThread(cutThread,"Frying"),"scrambleThread");

        // Not affected by the thread startup sequence        ();
        ();
        ();
        ();
        
        // The main thread can be executed first before starting: Buying vegetables        ("Start preparation...");
    }

    public static class CookingThread implements Runnable{
        private final Thread thread;
        private final String job;

        public CookingThread(Thread thread, String job){
             = thread;
             = job;
        }
        @Override
        public void run() {
            String name = ().getName()+":";
            try {
                ();

                (name + job + "start");
                (1000);
                (name + job + "Finish");
                (1000); // Be lazy            } catch (InterruptedException e) {
                ();
            }
        }
    }
}

Execution result: main > buyThread > washThread > cutThread > scrambleThread > end

Begin preparing...
buyThread: The grocery shopping starts
buyThread: The grocery shopping ends
washThread: Washing vegetables begins
washThread: The end of washing vegetables
cutThread: Cut vegetables to start
cutThread: The end of cutting vegetables
scrambleThread: The cooking starts
scrambleThread: The end of the cooking

Thread priority

Set the priority of the current thread. The higher the thread priority, the more times the thread may be executed. The priority of Java thread is represented by integers, and the priority range is 1-10, and the default is 5.

setPriority(int) method: set the priority of the thread.

getPriority method: get the priority of the thread.

public static void main(String[] args) {

    Thread thread = new Thread(() -> {
        ("Thread 1");
    });
    (10);
    Thread thread1 = new Thread(() -> {
        ("Thread 2");
    });
    (1);
    ();
    ();

    ("The default priority of threads is=" + ().getPriority());

}

Thread interrupt

Use the interrupt() method to set the thread interrupt flag =true to cause an interrupt signal to be thrown when the thread is "blocked". If the thread is in a blocking, waiting for wakeup or timeout waiting state (, and), it will receive an InterruptedException, thus ending the state in advance. Conversely, if the thread is in the "RUNNABLE" state, the interrupt flag will have no effect.

Case 1: Thread interrupt is valid

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        ("Thread 1");
        try {
            // The alarm clock rings after 1 minute            (60000);
            ("The alarm clock is ringing");
        } catch (InterruptedException e) {
            // Exit the timeout waiting state early            ("An exception occurred, I woke up in advance, the alarm clock did not ring and turned off manually");
        }

        ("Continue to execute the subsequent program of the thread...");

    });
    (1);
    ();
    ();
    ("The main thread sets the thread terminal status to "+());
}

Execution results:

The main thread sets the thread terminal status to true
Thread 1
An abnormality occurred, I woke up in advance, the alarm clock did not ring and turned off manually
Continue to execute the subsequent program of the thread...

Case 2: Thread interrupt is invalid

public static void main(String[] args) {
    Thread thread1 = new Thread(() -> {
        ("Thread" + ().getName());
        while (true) {
            (().getState() + "\t");
        }
    });
    ();
    ();
}

Execution result: The thread keeps printing its own status as RUNNABLE.

The above is a detailed explanation of common operations in Java threads. For more information about Java thread operations, please pay attention to my other related articles!