{System.out.println("Thread name="+Thread.currentThread().getName());},threadName);//set method//thread.setName"/> {System.out.println("Thread name="+Thread.currentThread().getName());},threadName);//set method//thread.setName">

Home  >  Article  >  Java  >  What are the commonly used operations of Java threads?

What are the commonly used operations of Java threads?

WBOY
WBOYforward
2023-04-24 11:55:07895browse

Common operations of threads

Set thread name: setName()

Get thread name: getName()

Thread unique Id: getId()

// 自定义线程名称
String threadName = "threadName";
// 构造方法方式
Thread thread = new Thread(() -> {
    System.out.println("线程名=" + Thread.currentThread().getName());
},threadName);
// set方法方式
// thread.setName(threadName);
System.out.println("线程唯一Id=" + thread.getId());

Thread startup: start()

Judge whether the thread is alive: isAlive()

// 线程启动
thread.start();
System.out.println("是否为存活线程=" + thread.isAlive());

Thread method: run() /call()

After the thread is started, it will to call the method. What the thread wants to do is written in the run/call method. There is no need to call it directly. After the thread starts, it will call run()/call(). If the program directly calls run/call without starting the thread, then it does not belong to multi-thread programming, but it belongs to the current thread to directly call ordinary methods.

Get the current thread object: currentThread()

To operate the non-static method of the current thread, you must first get the thread object

// 获取当前线程对象
Thread currentThread = Thread.currentThread();
// 对当前线程做一些操作
System.out.println(currentThread.getName());
try {
    // sleep 静态方法则不需要
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

About the state control of the thread (life Period) operation 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 for other threads. If there are no user threads in the process, then the daemon thread has no meaning, and the JVM will also end. Typical daemon threads include the JVM's garbage collection thread, and the startup of the operating system will also start the daemon threads of various modules.

Set the thread as a daemon thread: setDaeman()

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

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        System.out.println("线程名="+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 这一句不会打印出来,因为main线程(目前唯一的普通线程)等待1秒后已经结束了
        System.out.println("守护线程的状态=" + Thread.currentThread().getState());
    });
    // 守护线程
    thread.setDaemon(true);
    // 线程启动
    thread.start();
    System.out.println("是否为守护线程=" + thread.isDaemon());
}

Thread serialization

The thread executing the join() method enters the waiting wake-up state (WAITING) until the thread calling the method ends and then changes from the waiting wake-up state to the runnable state (RUNNABLE). The join() method is a method in the Thread class. The bottom layer is to use the wait() method to realize thread waiting. When the thread isAlive() is false,

realizes the serialization of the thread: one thread calls another Join() of a thread object to implement thread serialization execution.

For example: a good dish

public class DemoCooking {
    
    public static void main(String[] args) {
        Thread mainThread = Thread.currentThread();
        // 1.买菜
        Thread buyThread = new Thread(new CookingThread(mainThread,"买菜"),"buyThread");
        // 2.洗菜
        Thread washThread = new Thread(new CookingThread(buyThread,"洗菜"),"washThread");
        // 3.切菜
        Thread cutThread = new Thread(new CookingThread(washThread,"切菜"),"cutThread");
        // 4.炒菜
        Thread scrambleThread = new Thread(new CookingThread(cutThread,"炒菜"),"scrambleThread");

        // 不受线程启动顺序的影响
        scrambleThread.start();
        washThread.start();
        cutThread.start();
        buyThread.start();
        
        // main线程先执行完才可以开始:买菜
        System.out.println("开始准备……");
    }

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

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

                System.out.println(name + job + "开始");
                Thread.sleep(1000);
                System.out.println(name + job + "结束");
                Thread.sleep(1000); // 偷懒下
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

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

Start preparation ... End of dish
scrambleThread: Start of stir-fry
scrambleThread: End of stir-fry


Thread priority

Set the priority of the current thread. The higher the thread priority, the thread may get The more times it is executed, the priority of the Java thread is represented by an integer. 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(() -> {
        System.out.println("线程1");
    });
    thread.setPriority(10);
    Thread thread1 = new Thread(() -> {
        System.out.println("线程2");
    });
    thread1.setPriority(1);
    thread.start();
    thread1.start();

    System.out.println("线程默认的优先级为=" + Thread.currentThread().getPriority());

}

Thread interrupt

Use the interrupt() method to set the thread interrupt flag = true, so that an interrupt signal is thrown when the thread is "blocked". If the thread is blocked, waiting for wake-up, or timeout waiting state (Object.wait, Thread.join and Thread.sleep), then it will receive an interrupt exception (InterruptedException) and end the state early. On the other hand, if the thread is in the "RUNNABLE" state, the interrupt flag will have no effect.

Case 1: Thread interruption is valid

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        System.out.println("线程1");
        try {
            // 闹钟1分钟后响
            Thread.sleep(60000);
            System.out.println("闹钟响了");
        } catch (InterruptedException e) {
            // 提前退出超时等待状态
            System.out.println("发生异常,提前醒了,闹钟没响手动关了");
        }

        System.out.println("继续执行该线程的后续程序……");

    });
    thread.setPriority(1);
    thread.start();
    thread.interrupt();
    System.out.println("main线程将thread 终端状态设置为 "+thread.isInterrupted());
}

Execution result:

The main thread sets the thread terminal status to true

Thread 1

An exception occurs , woke up early, the alarm did not sound and manually turned it off

Continue to execute the subsequent program of the thread... The thread keeps printing its status as RUNNABLE.

The above is the detailed content of What are the commonly used operations of Java threads?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete