Processes and threads

process

Before we talk about multithreading, we need to understand what a process is. A process is the basic unit of CPU allocation and an instance of program execution.

thread

Thread is the basic unit of CPU scheduling and execution. A process can be composed of multiple threads. Each thread has its own stack and local variables. For a single-core CPU, multithreading is simply multiple threads switching back and forth between the same CPU. For multi-core cpus, it is possible for multiple threads to execute simultaneously.

Thread creation

Implement the Runnable interface

Define a class that implements the Runnable interface, overriding the run() method, and wrapping it with the Thread class when used

Implement Callable interface

Implement the Callable interface, override its call() method, and wrap it as FutureTask

Inherits from Thread

Define a class that inherits from Thread and then overrides its run() method

A thread of a normal Java program

Let’s take a look at the number of threads in a normal Java application. The following code can be interpreted as starting a process at startup. The number of printed processes is the number of threads used to start a Java process

public class MultiThread {
    public static void main(String []args) {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false.false);
        for (ThreadInfo info: threadInfos) {
            System.out.println("[" + info.getThreadId() + "]"+ info.getThreadName()); }}} the output is [5] Monitor Ctrl-Break
[4] Signal Dispatcher      // Distribution handles threads sent to the JVM
[3] Finalizer              // Call the thread of the object Finalize method
[2] Reference Handler      // Clear the thread of Reference
[1] main                   // The main thread, the application entry
Copy the code

The main thread

This is the current thread of execution

Reference Handler

The VM is created after the main thread is created, and it has the highest priority and is mainly used to deal with garbage collection of the reference objects themselves (soft, weak, virtual)

Finalizer

It is mainly used to call the Finalize () method of objects before garbage collection.

Signal Dispatcher

Monitor Ctrl-Break

Running Java programs using development tools of the IDEA class will occur

See more Java thread typesifeve.com/jvm-thread/

Thread state

In many articles, threads are divided into five states. In fact, from the perspective of the operating system, not only threads, but also processes can be divided into these five states. Let’s look at the division of the five states

Partitioning thread state from an operating system perspective

New

The New method is called to create a thread

A Runnable state

Running state. Java threads refer to the ready state and running state of the operating system as Runnable state. Ready state is a thread that is still waiting for CPU allocation after calling its start method.

Running state

The thread has acquired CPU resources and is in a running state

blocking

After the WAIT method is invoked, a thread is blocked and needs to use notify/notifyAll of another thread to wake up the thread. The thread does not run immediately and needs to wait for CPU resources to start running

The destruction

When a thread completes execution, is forcibly terminated, or is abnormal, it is destroyed and resources are released

Thread state partitioning in the JVM

Thread state is defined in the Thread class. The code is as follows:

public enum State {
    /** * Thread state for a thread which has not yet started. */
    NEW,

    /** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */
    RUNNABLE,

    /**
     * Thread state for a thread blocked waiting for a monitor lock.
     * A thread in the blocked state is waiting for a monitor lock
     * to enter a synchronized block/method or
     * reenter a synchronized block/method after calling
     * {@link Object#wait() Object.wait}.
     */
    BLOCKED,

    /**
     * Thread state for a waiting thread.
     * A thread is in the waiting state due to calling one of the
     * following methods:
     * <ul>
     *   <li>{@link Object#wait() Object.wait} with no timeout</li>
     *   <li>{@link #join() Thread.join} with no timeout</li>
     *   <li>{@link LockSupport#park() LockSupport.park}</li>
     * </ul>
     *
     * <p>A thread in the waiting state is waiting for another thread to
     * perform a particular action.
     *
     * For example, a thread that has called <tt>Object.wait()</tt>
     * on an object is waiting for another thread to call
     * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
     * that object. A thread that has called <tt>Thread.join()</tt>
     * is waiting for a specified thread to terminate.
     */
    WAITING,

    /**
     * Thread state for a waiting thread with a specified waiting time.
     * A thread is in the timed waiting state due to calling one of
     * the following methods with a specified positive waiting time:
     * <ul>
     *   <li>{@link #sleep Thread.sleep}</li>
     *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
     *   <li>{@link #join(long) Thread.join} with timeout</li>
     *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
     *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
     * </ul>
     */
    TIMED_WAITING,

    /** * Thread state for a terminated thread. * The thread has completed execution. */
    TERMINATED;
}
Copy the code

Threads are divided into six states

NEW

Create a thread

Runnable

Java threads collectively refer to the ready and running states of the operating system layer as Runnable states

The blocking state

The thread blocks the lock

Wait state

When a thread enters this state after executing wait(), the thread in this state must wait for other threads to take specific actions before changing the current state.

Timeout wait state

Unlike the wait state, this state can automatically return to the state state after a timeout

Termination status

Indicates that the thread is complete

The following diagram, from The Art of Concurrent Programming in JAVA, shows the switching between several states of a thread.

Methods related to thread state changes

start

When the start method is called, the thread becomes runnable

wait

When a thread is called to wait, it surrenders its lock and enters the wait queue, or blocked state

notify/notifyAll

Wakes up a single thread or all threads waiting on this object monitor

yield

When this method is called, the thread abandons the CPU time slice and moves from the running state to the runnable state. This method does not surrender the lock

sleep

The current thread enters the blocking state, but does not release the held lock. In contrast to the Yeild method, a thread that executed the sleep method does not execute for a specified period of time, whereas a thread that executed the Yeild method may execute again after it has reached the executable state.

join

Calling join on t2 in T1 will wait for t2 to complete, and the current thread will block

Communication between threads

Shared variables

Multiple threads access shared variables to achieve communication between threads, using volatile, synchronized mechanism to ensure the correctness of data

Wait notification mechanism

Wait notification mechanism, that is, use wait/notify, notifyAll to implement communication between threads

Pipe input/output

public class Piped {
    public static void main(String args[]) throws IOException {
        PipedWriter out = new PipedWriter();
        PipedReader in = new PipedReader();
        out.connect(in);
        Thread printThread = new Thread(new Print(in), "PrintThread");
        printThread.start();
        int receive = 0;
        try {
            while((receive = System.in.read()) ! = -1) { out.write(receive); }}finally{ out.close(); }}static class Print implements Runnable {
        private PipedReader in;
        public Print(PipedReader in) {
            this.in = in;
        }
        public void run(a) {
            int received = 0;
            try {
                while((received = in.read()) ! = -1) {
                    System.out.print((char)received); }}catch (IOException e) {

            } 
        }
    }
}

Copy the code

The above code is from The Art of Concurrent Programming in Java

Thread.join()

Calling join on t2 in T1 will wait for t2 to complete, and the current thread will block