>  기사  >  Java  >  Java 동시성에서 스레드의 사용 및 기본 개념

Java 동시성에서 스레드의 사용 및 기본 개념

黄舟
黄舟원래의
2017-09-30 10:36:121573검색


스레드 정의

LWP(Lightweight Process)라고도 불리는 스레드는 프로그램 실행 흐름의 가장 작은 단위입니다. 표준 스레드는 스레드 ID, 현재 명령 포인터(PC), 레지스터 세트 및 스택으로 구성됩니다. 명시적인 조정 메커니즘이 없으면 스레드는 서로 독립적으로 실행됩니다. 모든 프로그램에는 최소한 하나의 스레드가 있습니다. 프로그램에 스레드가 하나만 있으면 프로그램 자체입니다.的 스레드는 프로세스의 개체이며 시스템에 의해 독립적으로 예약되고 분산되는 기본 단위입니다. 스레드는 프로세스가 소유한 모든 리소스를 공유하므로(프로세스의 메모리 주소 공간을 공유) 이러한 스레드는 모두 동일하게 액세스할 수 있습니다. 변수를 사용하고 동일한 힙에 개체를 할당합니다. 이는 프로세스 간에 데이터를 공유하는 것보다 더 세분화된 구현이 필요합니다. 이 동기화 메커니즘이 없으면 다중 스레드 상황에서 예측할 수 없는 결과가 발생합니다.

                    하나의 스레드가 다른 스레드를 만들고 삭제할 수 있으며, 동일한 프로세스의 여러 스레드가 동시에 실행될 수 있습니다. 스레드 간의 상호 제약으로 인해 스레드는 작업에 불연속성을 나타냅니다. 스레드에는 준비, 차단, 실행이라는 세 가지 기본 상태도 있습니다. 준비 상태는 스레드가 실행할 모든 조건을 갖추고 있고 논리적으로 실행될 수 있으며 프로세서를 기다리고 있음을 의미합니다. 실행 상태는 스레드가 프로세서를 점유하고 실행 중임을 의미합니다. 이벤트(예: 세마포어) 및 논리를 시행할 수 없습니다.

스레드는 프로그램의 단일 순차 제어 프로세스입니다. 프로세스 내에서 상대적으로 독립적이고 스케줄링 가능한 실행 단위입니다. 시스템이 독립적으로 CPU를 스케줄링하고 할당하는 기본 단위입니다. 단일 프로그램에서 여러 작업을 완료하기 위해 동시에 여러 스레드를 실행하는 것을 멀티스레딩이라고 합니다.

Java의 스레드

Java 프로그램의 진입점은 메인 메소드를 호출하여 실행을 시작한 다음 코드 논리에 따라 실행되는 것 같습니다. Java 프로그램은 본질적으로 다중 스레드 프로그램입니다. 실제로 main이라는 스레드는 다른 스레드와 별도로 실행됩니다.

코드(Java 동시 프로그래밍 기술 참조)

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());
        }
    }
}

반환 결과

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

스레드 상태

소스 코드 정의

    /**
     * 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;
    }

상태 전환 다이어그램


Java 동시성에서 스레드의 사용 및 기본 개념
상태 설명


Java 동시성에서 스레드의 사용 및 기본 개념
Java 멀티의 준비, 실행 및 종료 상태 -스레드

준비 상태가 실행 상태로 변환되는 경우: 이 스레드가 프로세서 리소스를 가져오는 경우

실행 상태가 준비 상태로 변환되는 경우: 이 스레드가 작업 중에 Yield() 메서드를 적극적으로 호출하거나 프로세서 리소스를 잃는 경우.

실행 상태는 종료 상태로 전환됩니다. 이 스레드의 실행 본문이 실행을 완료하거나 예외가 발생하는 경우입니다.
여기서 특별히 주의해야 할 점은 스레드의 Yield() 메서드가 호출되면 스레드가 실행 상태에서 준비 상태로 전환되지만 다음에 CPU에 의해 예약된 준비 상태의 스레드가 어느 정도 스레드 A가 Yield() 메서드를 호출한 후에도 CPU는 여전히 스레드 A를 예약합니다.

실제 비즈니스 요구로 인해 특정 시간에 특정 스레드의 실행을 종료하고 데드 상태로 전환해야 하는 경우가 많습니다. 현재 가장 일반적인 방법은 조건이 충족되면 스레드 실행 본문이 빠르게 실행됩니다(

더 이상 실행 메서드를 실행하지 않음

). 스레드를 종료합니다. . 상태 분석 - jvisualvm

코드 참조(Java 동시 프로그래밍 기술)

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();
        }
    }
}

덤프 결과

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)

위 내용은 Java 동시성에서 스레드의 사용 및 기본 개념의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.