Thread源码浅析


一、Thread类的数据结构

class Thread implements Runnable {
    //...
    private char        name[];//线程的名字
    private int         priority;//线程的优先级
    //...
    /* Whether or not the thread is a daemon thread. */
    private boolean     daemon = false;  //标记是否为守护线程
    /* What will be run. */
    private Runnable target;//线程类的父接口
    /* For autonumbering anonymous threads. */
    private static int threadInitNumber;//在匿名线程的时候使用
    //...
}
二、构造器

Thread有比较多的构造器,比较常用的如下:

public Thread()
public Thread(Runnable target)
public Thread(String name)
public Thread(Runnable target, String name)
三、线程的优先级的等级

/**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;
四、主要的方法

yield():提醒调度器当前线程放弃处理
sleep(long min):是线程睡眠min毫秒,这个线程将不会丢失锁
start():启动线程,JVM会调用run方法
interrupt():中断线程
interrupted():判断是否无边框
isAlive():判断线程是否还存活
join(long):等到直到线程死去,如果参数为0,表示永久的等待->内部采用wait()实现

五、线程的启动

第一种:
Thread t = SubThread();
t.start()
注:SubThread是继承Thread的类
由于JVM会调用run方法
Thread类的run方法:

public void run() {
        if (target != null) {
            target.run();
        }
    }
默认构造器

public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }
private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null);
    }
可以知道target为null
如果子类没有重写父类的run方法,JVM会调用一个空的run方法,一般使用线程都要重新run方法
第二种方式:
Thread t = Thread(new TestRun());
t.start()
注:TestRun实现了Runnable接口
先有必要看一下Runnable接口
Runnable接口很简洁.

public
interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
run方法为抽象方法,所以必须要实现run接口
这种实现可以得出:
1.可以得出target不为空
2.target.run()会调用子类的run方法也就是TestRun类中实现的run方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值