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