JAVA多线程学习(2) Thread类

上一篇写完了创建线程的几种方式及区别,这篇写下Thread类常用方法,如果有什么不对的地方,欢迎指正

Thread类

Thread类作为JAVA线程的基础类,包含了线程常用的方法,如启动线程,停止线程,是否存活等等,并且Thread类也是实现了Runnable接口

此处应该有图

Thread类的成员变量及构造函数

成员变量

private volatile String name;
	//优先级
    private int            priority;
    private Thread         threadQ;
    private long           eetop;

    /* Whether or not to single_step this thread. */
    private boolean     single_step;

  	//是否守护线程
    private boolean     daemon = false;

    /* JVM state */
    private boolean     stillborn = false;

    //runnable实现
    private Runnable target;

    /* 线程组 */
    private ThreadGroup group;

    /* ClassLoader */
    private ClassLoader contextClassLoader;

    /* The inherited AccessControlContext of this thread */
    private AccessControlContext inheritedAccessControlContext;

    /* For autonumbering anonymous threads. */
    private static int threadInitNumber;
 
    //这个就很重要了,threadLocals,用来存放本地线程变量
    ThreadLocal.ThreadLocalMap threadLocals = null;

    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

    /*
   		当前线程栈深度
     */
    private long stackSize;

    /*
     * JVM-private state that persists after native thread termination.
     */
    private long nativeParkEventPointer;

    /*
     * Thread ID
     */
    private long tid;

    /* For generating thread ID */
    private static long threadSeqNumber;

  	//线程状态
 	private volatile int threadStatus = 0;

构造函数

来一张大图
JAVA多线程学习(2) Thread类_第1张图片
大致可以看出Thread构造接受Runnable实现,并且可以直接指定线程名称以及线程组

Thread方法

  1. Sleep

    public static native void sleep(long millis) 
    		throws InterruptedException;
    

    使当前线程休眠,可能会被打断,并且抛出InterruptedException异常

    @Test
        public void sleep() throws InterruptedException {
            System.out.println(System.nanoTime());
            Thread.sleep(1000);
            System.out.println(System.nanoTime());
        }
       
    
    63004150579865
    63005155218737
    
  2. Join

     join方法可以理解为A线程方法体内调用了B线程的join方法,
     那么A线程就会阻塞直到B方法执行完并且B线程死亡才开始接着执行A线程接下来的代码。
    

    join方法有一个很经典的面试题,如何让线程按照顺序执行,这道题最简单的解法就是使用join方法。

    https://leetcode-cn.com/problems/print-in-order/

    瞅一眼javadoc

    /**
         * Waits for this thread to die.
         *
         * 

    An invocation of this method behaves in exactly the same * way as the invocation * *

    * {@linkplain #join(long) join}{@code (0)} *
    * * @throws InterruptedException * if any thread has interrupted the current thread. The * interrupted status of the current thread is * cleared when this exception is thrown. */ public final void join() throws InterruptedException { join(0); }
     Waits for this thread to die.
    

    从doc可以看出等待这个线程死亡,也就是说调用了thread.join方法就会阻塞一直等待

    顺带把上面leetcode的体解下

    public class Join {
    
        @Test
        public void join() throws InterruptedException {
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                        System.out.println("1");
                }
            });
    
            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        t1.join();
                        System.out.println("2");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    
            Thread t3 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        t2.join();
                        System.out.println("3");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t2.start();
            t1.start();
            t3.start();
        }
    }
    

    JAVA多线程学习(2) Thread类_第2张图片

  3. start

    start方法用来启动一个线程,不能直接执行run方法。
    
  4. currentThread

     获取当前线程实例
    
  5. isAlive

    判断当前线程是否
    
  6. isDaemon

     判断是否是守护线程
    

总结

1. thread类是java线程的基础类,无论是callable接口还是runnable接口最终都离不开thread类做载体,
2. thread构造方法可以直接设置线程名,设置线程组,或者直接设置Runnable实例对象
3. 通过start方法启动一个线程
4. Thread类常用方法start,join,sleep等。

你可能感兴趣的:(多线程)