Thread类学习

Posted gsanye

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thread类学习相关的知识,希望对你有一定的参考价值。

Thread类定义:

public class Thread implements Runnable

Thread类属性定义:

/***线程名称*/
private volatile String name;

/**
*线程优先级 
*MIN_PRIORITY = 1
*NORM_PRIORITY = 5
*MAX_PRIORITY = 10
*/
private int priority;

/***守护线程标识*/
private boolean daemon = false;

/***目标任务*/
private Runnable target;

/**线程初始化编号**/
private static int threadInitNumber;

/**ThreadLocalMap ThreadLocal 存储Map*/
ThreadLocal.ThreadLocalMap threadLocals = null;

/**ThreadLocalMap 可继承的 ThreadLocal 存储Map*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

/**stack size 初始化为0,VM可会忽略*/
private final long stackSize;

/**线程id*/
private final long tid;

/** 生成tid For generating thread ID */
private static long threadSeqNumber;

/** 当前线程状态*/
private volatile int threadStatus;

/** 中断状态使用 用于NIO操作中断*/
private volatile Interruptible blocker;
/**设置中断状态 锁监视器 防止线程阻塞在I/O操作*/
private final Object blockerLock = new Object();

// 特殊设置的为捕捉异常处理器 需要设置null unless explicitly set
private volatile UncaughtExceptionHandler uncaughtExceptionHandler;

// 默认的未捕捉异常处理器 需要设置 null unless explicitly set
private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;

Thread方法:

yield:
/**尝试暗示调度器当前线程可以让出处理器,用于测试或者重现静态条件错误,也可用于设计并发控制*/
public static native void yield()

sleep:

/**
*停止当前线程执行去休眠
*不会失去已有的监视器(does not lose ownership of any monitors)
*当前线程被别的线程中断时抛出异常并清楚中断状态
*/
public static native void sleep(long millis) throws InterruptedException;

new:

/**
*创建一个新的线程
*ThreadGroup线程所属组(无用)
*target 目标执行任务
*name 线程名称
*stackSize 栈大小
*acc :AccessControlContext 访问控制上下文
*inheritThreadLocals: boolean 是否可以继承此线程的父线程(即创建这个线程的运行线程 parent = currentThread())的 inheritThreadLocalMap
*/
private Thread(ThreadGroup g, Runnable target, String name,
                   long stackSize, AccessControlContext acc,
                   boolean inheritThreadLocals)

start:

/**
*启动此线程,JVM将调用此线程的Run()方法
*结果将是两个线程并行,一个调用start()方法的线程,一个调用此线程Run()方法的线程
*一个线程只能start一次(否则:IllegalThreadStateException),一个线程一旦完成,可能不会再重新启动
*/
public synchronized void start()

run:

/**
*run方法:如果有目标Runnable将执行,也可重写此方法
*/
public void run() 
        if (target != null) 
            target.run();
        
    

exit:

/**
*由系统调用,提供实际退出前的清理机会
*/
private void exit()

stop:

/**
*强制停止线程执行
*放弃说有监视器(stop causes it to unlock all of the monitors that it has locked )
*已废弃
*/

public final void stop()

interrupt:

/**
*中断此线程,如果非当前线程中断自己,将进行访问检查
*如果线程阻塞在:Object.wait()、wait(long)、wait(long,int) 或者
*       Thread.join()、join(long)、jion(long,int)、sleep(long),sleep(long,int)
*       线程的中断状态将被清除,并且收到一个InterruptedException *如果线程阻塞在:NIO的InterruptibleChannel 的I/O操作上
*        线程的中断状态将被设置,并且收到一个ClosedByinterrupException
*如果线程阻塞在:NIO的Selector上
*        线程的中断状态将被设置,并返回
*如果以上条件都不成立,那么线程中断状态将被设置
*/ public void interrupt() if (this != Thread.currentThread()) checkAccess(); // thread may be blocked in an I/O operation 线程可能阻塞在I/O synchronized (blockerLock) Interruptible b = blocker; if (b != null) interrupt0(); // set interrupt status b.interrupt(this); return; // set interrupt status native 方法设置中断状态 interrupt0();

static interrupted

/**
*清除线程中断状态,并返回清除前的线程中断状态
*/
public static boolean interrupted() 
        return currentThread().isInterrupted(true);
    

isInteruupted

/**
*测试当前线程中断状态
*/
public boolean isInterrupted() 
        return isInterrupted(false);
    

isAlive

/**
*线程已经启动并且还未死亡时为存活状态
*/
public final native boolean isAlive()

suspend

/**
*线程挂起 已废弃,容易引发死锁
*/
public final void suspend() 
        checkAccess();
        suspend0();
    

resume

/**
*恢复线程 已废弃,与挂起方法结合,容易死锁
*/
public final void resume() 
        checkAccess();
        resume0();
    

setPriority

/**
*设置线程优先级
*访问检查与参数校验
*设置优先级为min(group.max,newPrioritr)
*/
public final void setPriority(int newPriority) 
        ThreadGroup g;
        checkAccess();
        if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) 
            throw new IllegalArgumentException();
        
        if((g = getThreadGroup()) != null) 
            if (newPriority > g.getMaxPriority()) 
                newPriority = g.getMaxPriority();
            
            setPriority0(priority = newPriority);
        
    

getPriority

/**
*返回优先级
*/
public final int getPriority() 
        return priority;
    

setName

/**
*设置线程名称
*/
public final synchronized void setName(String name) 
        checkAccess();
        if (name == null) 
            throw new NullPointerException("name cannot be null");
        

        this.name = name;
        if (threadStatus != 0) 
            setNativeName(name);
        
    

getName

/**
*获取线程名称
*/
public final String getName() 
        return name;
    

join

/**
*使用循 环调用 Object.wait(long) 实现(阻塞方法调用线程,等待此线程对象运行结束),条件:当线程存活的时候
*millis = 0 意味着一直等待
*不建议在线程上使用Object.notify、notifyAll,这样会唤醒此方法再次进入循环判断
*tips:synchronized 获取shis监视器,后续调用Object.wait需要
*/ public final synchronized void join(long millis) throws InterruptedException long base = System.currentTimeMillis(); long now = 0; if (millis < 0) throw new IllegalArgumentException("timeout value is negative"); if (millis == 0) //判断是否带有超时时间.为0则为一直等待 while (isAlive()) //线程未结束则一直等待 wait(0);//调用Object.wati方法实现阻塞 else while (isAlive()) //等待超时结束 long delay = millis - now; if (delay <= 0) //防止中途被notify break;//等待时间结束 wait(delay);//等待 now = System.currentTimeMillis() - base;
/**
*参见上面方法
*/
public final void join() throws InterruptedException
join(0);

setDaemon

/**
*标记此线程为守护线程或用户线程,如果线程已经启动则:IllegalThreadStateException
*当只有守护线程时候,虚拟机退出
*/
    public final void setDaemon(boolean on) 
        checkAccess();
        if (isAlive()) 
            throw new IllegalThreadStateException();
        
        daemon = on;
    

getDaemon

/**
*返回此线程是否为守护线程
*/
public final boolean isDaemon() 
        return daemon;
    

checkAccess

/**
*访问检查
*/
    public final void checkAccess() 
        SecurityManager security = System.getSecurityManager();
        if (security != null) 
            security.checkAccess(this);
        
    

toString

/**
*toString方法:Thread[name,priority‘,groupName‘]
*
*/
    public String toString() 
        ThreadGroup group = getThreadGroup();
        if (group != null) 
            return "Thread[" + getName() + "," + getPriority() + "," +
                           group.getName() + "]";
         else 
            return "Thread[" + getName() + "," + getPriority() + "," +
                            "" + "]";
        
    

getContextClassLoader

/**
*获取线程的上下文类加载器
*/
    public ClassLoader getContextClassLoader() 
        if (contextClassLoader == null)
            return null;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) 
            ClassLoader.checkClassLoaderPermission(contextClassLoader,
                                                   Reflection.getCallerClass());
        
        return contextClassLoader;
    

setcontextClassLoader

/**
*设置线程的上下文类加载器
*/
    public void setContextClassLoader(ClassLoader cl) 
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) 
            sm.checkPermission(new RuntimePermission("setContextClassLoader"));
        
        contextClassLoader = cl;
    

static holdsLock

/**
*断言当前线程是否持有某个对象的监视器
*/
public static native boolean holdsLock(Object obj);

getStackTrace

/**
*获取此线程的栈帧元素
*/
public StackTraceElement[] getStackTrace()

getAllStackTraces

/**
*获取所有的线程的栈帧元素
*/
     // check for getStackTrace permission
        SecurityManager security = System.getSecurityManager();
        if (security != null) 
            security.checkPermission(
                SecurityConstants.GET_STACK_TRACE_PERMISSION);
            security.checkPermission(
                SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
        

        // Get a snapshot of the list of all threads
        Thread[] threads = getThreads();
        StackTraceElement[][] traces = dumpThreads(threads);
        Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
        for (int i = 0; i < threads.length; i++) 
            StackTraceElement[] stackTrace = traces[i];
            if (stackTrace != null) 
                m.put(threads[i], stackTrace);
            
            // else terminated so we don‘t put it in the map
        
        return m;
    

getId

/**
*返回tid
*/
public long getId() 
        return tid;
    

getState

/**
*获取此线程的状态
*/
public State getState() 
        // get current thread state
        return jdk.internal.misc.VM.toThreadState(threadStatus);
    

setDefaultuncaughtExceptionhandler

/**
*设置所有线程的默认未捕捉异常处理器
*/
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) 
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) 
            sm.checkPermission(
                new RuntimePermission("setDefaultUncaughtExceptionHandler")
                    );
        

         defaultUncaughtExceptionHandler = eh;
     
//获取默认异常处理器
public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
return defaultUncaughtExceptionHandler;
//获取异常处理器
public UncaughtExceptionHandler getUncaughtExceptionHandler() 
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
//设置异常处理器
public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) 
checkAccess();
uncaughtExceptionHandler = eh;
//向处理程序发送异常
private void dispatchUncaughtException(Throwable e) 
getUncaughtExceptionHandler().uncaughtException(this, e);
 

 

 

 

 

 

 

 

 


以上是关于Thread类学习的主要内容,如果未能解决你的问题,请参考以下文章

JAVA学习笔记线程的生命周期及Thread类常用方法

java线程学习

Java并发--Thread类详情

java基础知识回顾之java Thread类学习-- 线程中断

Thread类的使用

java基础知识回顾之java Thread类学习--join方法的理解