Basic threading mechanism

Executor

Executor manages the execution of multiple asynchronous tasks without the programmer having to explicitly manage the life cycle of threads. Asynchronous here means that the execution of multiple tasks does not interfere with each other and does not need to be synchronized.

There are three main types of Executor:

  • CachedThreadPool: A task creates a thread;
  • FixedThreadPool: All tasks can only use fixed-size threads;
  • SingleThreadExecutor: Equivalent to FixedThreadPool of size 1.
public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 5; i++) {
        executorService.execute(new MyRunnable());
    }
    executorService.shutdown();
}

Daemon

The daemon thread is a thread that provides services in the background while the program is running, and is not an indispensable part of the program.

When all non-daemon threads end, the program is terminated, and all daemon threads are killed at the same time.

main() is a non-daemon thread.

Before the thread starts, use the setDaemon() method to set a thread as a daemon thread.

public static void main(String[] args) {
    Thread thread = new Thread(new MyRunnable());
    thread.setDaemon(true);
}

sleep()

The Thread.sleep(millisec) method sleeps the currently executing thread, and the unit of millisec is milliseconds.

sleep() may throw InterruptedException because the exception cannot be propagated back to main() across threads, so it must be handled locally. Other exceptions thrown in the thread also need to be handled locally.

public void run() {
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

yield()

The call to the static method Thread.yield() declares that the current thread has completed the most important part of the life cycle and can be switched to other threads for execution. This method is only a suggestion to the thread scheduler, and it only suggests that other threads with the same priority can run.

public void run() {
    Thread.yield();
}

Guess you like

Origin blog.csdn.net/qq_39331713/article/details/104951970