一、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方法。