Home  >  Article  >  Java  >  The use and basic concepts of threads in Java concurrency

The use and basic concepts of threads in Java concurrency

黄舟
黄舟Original
2017-09-30 10:36:121572browse


Thread definition

A thread, sometimes called a lightweight process (LWP), is the smallest unit of program execution flow. A standard thread consists of thread ID, current instruction pointer (PC), register set and stack. Without an explicit coordination mechanism, threads will execute independently of each other. Every program has at least one thread. If a program has only one thread, it is the program itself.

The thread is a entity in the process. It is the basic unit of independent scheduling and distribution by the system. The thread does not have system resources, only a little bit of resources in operation, but it can be the same as the same genus. Other threads of a process share all resources owned by the process (share the memory address space of the process), so these threads can access the same variables and allocate objects on the same heap, which requires a method of sharing between processes. A data sharing mechanism with finer data granularity. Without this synchronization mechanism, unpredictable consequences will occur in multi-threaded situations.

                                        One thread can create and destroy another thread, and multiple threads in the same process can execute concurrently. Due to the mutual constraints between threads, threads show discontinuity in their operation. Threads also have three basic states: ready, blocked and running. The ready state means that the thread has all the conditions to run, can run logically, and is waiting for the processor; the running state means that the thread occupies the processor and is running; the blocking state means that the thread is waiting for an event (such as a semaphore), and the logic is not enforceable.

A thread is a single sequential control process in a program. A relatively independent and schedulable execution unit within a process. It is the basic unit for the system to independently schedule and allocate the CPU. It refers to the scheduling unit of a running program. Running multiple threads at the same time to complete different tasks in a single program is called multithreading.

Threads in java

The entrance to a Java program is the main method. It starts execution by calling the main method, and then executes according to the code logic. It seems that no other threads are involved. In fact, Java programs are inherently In a multi-threaded program, executing a main method is actually a thread named main and other threads are executed separately. The reference code is as follows:

Code (refer to the art of java concurrent programming)

package com.sunld;import java.lang.management.ManagementFactory;import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;/**
 * @Title: TestMainThread.java
 * @Package com.sunld
 * <p>Description:</p>
 * @author sunld
 * @version V1.0.0 
 * <p>CreateDate:2017年9月28日 下午3:54:19</p>
*/public class TestMainThread {

    public static void main(String[] args) {        // 获取Java线程管理MXBean
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();        // 不需要获取同步的monitor和synchronizer信息,仅获取线程和线程堆栈信息
        ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);        // 遍历线程信息,仅打印线程ID和线程名称信息
        for (ThreadInfo threadInfo : threadInfos) {
            System.out.println("[" + threadInfo.getThreadId() + "] " + 
                    threadInfo.getThreadName());
        }
    }
}

Return results

[5] Attach Listener//附加监听
[4] Signal Dispatcher//分发处理发送给JVM信号的线程
[3] Finalizer//调用对象finalize方法的线程
[2] Reference Handler清除Reference的线程
[1] mainmain线程,用户程序入口

Thread status

Source code definition

    /**
     * A thread state.  A thread can be in one of the following states:
     * <ul>
     * <li>{@link #NEW}<br>
     *     A thread that has not yet started is in this state.
     *     </li>
     * <li>{@link #RUNNABLE}<br>
     *     A thread executing in the Java virtual machine is in this state.
     *     </li>
     * <li>{@link #BLOCKED}<br>
     *     A thread that is blocked waiting for a monitor lock
     *     is in this state.
     *     </li>
     * <li>{@link #WAITING}<br>
     *     A thread that is waiting indefinitely for another thread to
     *     perform a particular action is in this state.
     *     </li>
     * <li>{@link #TIMED_WAITING}<br>
     *     A thread that is waiting for another thread to perform an action
     *     for up to a specified waiting time is in this state.
     *     </li>
     * <li>{@link #TERMINATED}<br>
     *     A thread that has exited is in this state.
     *     </li>
     * </ul>
     *
     * <p>
     * A thread can be in only one state at a given point in time.
     * These states are virtual machine states which do not reflect
     * any operating system thread states.
     *
     * @since   1.5
     * @see #getState
     */
    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;
    }

State transition diagram


The use and basic concepts of threads in Java concurrency
##State description


The use and basic concepts of threads in Java concurrency
Ready, running and death states of Java multi-threads

The ready state is converted to the running state: when this thread obtains processor resources ;

Running state transitions to ready state: when this thread actively calls the yield() method or loses processor resources during running.
The running state is converted to the death state: when the thread execution body completes execution or an exception occurs.
What needs special attention here is: when the yield() method of the thread is called, the thread transitions from the running state to the ready state, but which thread in the ready state is scheduled by the CPU next has a certain degree of randomness, so it may It may happen that after thread A calls the yield() method, the CPU still schedules thread A.

Due to actual business needs, it is often necessary to terminate the running of a thread at a specific time to make it enter a death state. At present, the most common method is to set a boolean variable. When the conditions are met, the thread execution body will be executed quickly (

will not execute the run method). In subsequent articles, we will introduce how to safely terminate a thread. . .

State analysis-jvisualvm

Code-reference (java concurrent programming art)

package com.sunld;

import java.util.concurrent.TimeUnit;/**
 * @Title: TestThreadState.java
 * @Package com.sunld
 * <p>Description:</p>
 * @author sunld
 * @version V1.0.0 
 * <p>CreateDate:2017年9月28日 下午5:14:27</p>
*/public class TestThreadState {
    public static void main(String[] args) {        
    new Thread(new TimeWaiting (), "TimeWaitingThread").start();        
    new Thread(new Waiting(), "WaitingThread").start();        // 使用两个Blocked线程,一个获取锁成功,另一个被阻塞
        new Thread(new Blocked(), "BlockedThread-1").start();        
        new Thread(new Blocked(), "BlockedThread-2").start();
    }    //该线程不断地进行睡眠
    static class TimeWaiting implements Runnable{
        @Override        
        public void run() {
            SleepUtils.second(100);
        }
    }    //该线程在Waiting.class实例上等待
    static class Waiting implements Runnable{

        @Override        
        public void run() {            
        while (true) {
                synchronized (Waiting.class) {                    
                try {
                        Waiting.class.wait();
                    }catch(InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }    //该线程在Blocked.class实例上加锁后,不会释放该锁
    static class Blocked implements Runnable {

        @Override        public void run() {
            synchronized (Blocked.class) {                
            while (true) {
                    SleepUtils.second(100);
                }
            }
        }
    }
}class SleepUtils{
    public static final void second(long seconds) {        
    try {
            TimeUnit.SECONDS.sleep(seconds);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}

dump results

2017-09-28 17:26:47Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.112-b15 mixed mode):

//BlockedThread-2线程获取到了Blocked.class的锁"BlockedThread-2" #13 prio=5 os_prio=0 tid=0x000000001f268000 nid=0x3754 waiting on condition [0x000000002009f000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)

//BlockedThread-1线程阻塞在获取Blocked.class示例的锁上"BlockedThread-1" #12 prio=5 os_prio=0 tid=0x000000001f266800 nid=0x89c waiting for monitor entry [0x000000001ff9f000]
   java.lang.Thread.State: BLOCKED (on object monitor)

//WaitingThread线程在Waiting实例上等待"WaitingThread" #11 prio=5 os_prio=0 tid=0x000000001f260800 nid=0x4d08 in Object.wait() [0x000000001fe9f000]
   java.lang.Thread.State: WAITING (on object monitor)

//TimeWaitingThread线程处于超时等待"TimeWaitingThread" #10 prio=5 os_prio=0 tid=0x000000001f25f000 nid=0x42ac waiting on condition [0x000000001fd9e000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)

The above is the detailed content of The use and basic concepts of threads in Java concurrency. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn