2021-10-09

Java Multithreaded Programming

Java provides built-in support for multithreaded programming. A thread refers to a single sequential control flow in a process. A process can have multiple threads concurrently, and each thread executes different tasks in parallel.

Multithreading is a special form of multitasking, but multithreading uses less resource overhead.

Another term related to threads is defined here - process: A process consists of memory space allocated by the operating system and contains one or more threads. A thread cannot exist independently, it must be part of a process. A process keeps running until all non-daemon threads have finished running.

Multithreading can satisfy programmers to write high-efficiency programs to make full use of the CPU.

life cycle of a thread

Thread is a dynamic execution process, it also has a process from birth to death.

The figure below shows the complete life cycle of a thread.

  • New state:

    After a thread object is created using the new keyword and the Thread class or its subclasses, the thread object is in a new state. It remains in this state until the program starts() the thread.

  • Ready state:

    When the thread object calls the start() method, the thread enters the ready state. The thread in the ready state is in the ready queue, waiting for the scheduling of the thread scheduler in the JVM.

  • Operating status:

    If the thread in the ready state acquires CPU resources, it can execute run() and the thread is in the running state. A running thread is the most complex, it can become blocked, ready and dead.

  • Blocking state:

    If a thread executes methods such as sleep (sleep), suspend (suspend), and loses the resources occupied, the thread enters the blocking state from the running state. The ready state can be re-entered after sleep time has elapsed or device resources have been acquired. Can be divided into three types:

    • Waiting for blocking: The thread in the running state executes the wait() method to make the thread enter the waiting-blocking state.
    • Synchronization blocking: The thread failed to acquire the synchronized synchronization lock (because the synchronization lock is occupied by other threads).
    • Other blocking: When an I/O request is issued by calling the thread's sleep() or join(), the thread enters the blocking state. When the sleep() state times out, join() waits for the thread to terminate or time out, or the I/O is processed, and the thread re-enters the ready state.
  • death status:

    A thread in the running state switches to the terminated state when it completes a task or when other termination conditions occur.

thread priority

Each Java thread has a priority, which helps the operating system determine the scheduling order of threads.

The priority of a Java thread is an integer ranging from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY).

By default, each thread is assigned a priority NORM_PRIORITY (5).

Threads with higher priority are more important to the program and should be allocated processor resources before lower priority threads. However, thread priority does not guarantee the order of thread execution and is very platform dependent.


create a thread

Java provides three ways to create threads:

  • By implementing the Runnable interface;
  • By inheriting from the Thread class itself;
  • Threads are created through Callable and Future.

Create a thread by inheriting from Thread

The second way to create a thread is to create a new class that extends the Thread class, and then create an instance of that class.

Inheriting classes must override the run() method, which is the entry point for the new thread. It must also call the start() method to execute.

Although this method is listed as a multi-threaded implementation, it is essentially an instance of the Runnable interface.

Thread method

The following table lists some important methods of the Thread class:

serial number Method description
1 public void start() causes the thread to start executing; the Java virtual machine calls the thread's run method.
2 public void run() If the thread is constructed using an independent Runnable run object, call the run method of the Runnable object; otherwise, the method does nothing and returns.
3 public final void setName(String name) Change the thread name to be the same as the parameter name.
4 public final void setPriority(int priority) changes the priority of the thread.
5 public final void setDaemon(boolean on) marks the thread as a daemon thread or a user thread.
6 public final void join(long millisec) waits for the thread to terminate for up to millis milliseconds.
7 public void interrupt() interrupts the thread.
8 public final boolean isAlive() Tests if the thread is alive.
serial number Method description
1 public static void yield() suspends the currently executing thread object and executes other threads.
2 public static void sleep(long millisec) Sleeps (suspends execution) the currently executing thread for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
3 public static boolean holdsLock(Object x) Returns true if and only if the current thread holds the monitor lock on the specified object.
4 public static Thread currentThread() returns a reference to the currently executing thread object.
5 public static void dumpStack() prints the current thread's stack trace to the standard error stream.

Create threads with Callable and Future

  • \1. Create an implementation class of the Callable interface, and implement the call() method. The call() method will act as the thread execution body and have a return value.
  • \2. Create an instance of the Callable implementation class, and use the FutureTask class to wrap the Callable object. The FutureTask object encapsulates the return value of the call() method of the Callable object.
  • \3. Create and start a new thread using the FutureTask object as the target of the Thread object.
  • \4. Call the get() method of the FutureTask object to obtain the return value after the execution of the child thread ends.

Comparison of three ways to create threads

  • \1. When creating multi-threads by implementing Runnable and Callable interfaces, the thread class only implements Runnable interface or Callable interface, and can also inherit other classes.
  • \2. When creating a multi-thread by inheriting the Thread class, the writing is simple. If you need to access the current thread, you don't need to use the Thread.currentThread() method, you can directly use this to get the current thread.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325342915&siteId=291194637