線程共包括一下5種狀態java
//工具的Java線程狀態, 初始化表示線程'還沒有啓動'
private volatile int threadStatus = 0;
//這個線程的組
private ThreadGroup group;
public synchronized void start() {
//若是線程不是"就緒狀態",則拋出異常!
if (threadStatus != 0)
throw new IllegalThreadStateException();
//將線程添加到ThreadGroup中
//通知組該線程即將啓動,這樣它就能夠添加到組的線程列表中,而且該組的未啓動計數能夠遞減
group.add(this);
boolean started = false;
try {
//經過該方法啓動線程
start0();
//設置標記
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
複製代碼
start()其實是經過本地方法start0()啓動線程的。而start0()會新運行一個線程,新線程會調用run()方法。安全
/* What will be run. */
private Runnable target;
public void run() {
if (target != null) {
target.run();
}
}
複製代碼
target是一個Runnable對象。run()就是直接調用Thread線程的Runnable成員的run()方法,並不會新建一個線程。bash
「synchronized方法」是用synchronized修飾方法,而 「synchronized代碼塊」則是用synchronized修飾代碼塊。多線程
@Override
public void run() {
while (true) {
try {
// 執行任務...
} catch (InterruptedException ie) {
// InterruptedException在while(true)循環體內。
// 當線程產生了InterruptedException異常時,while(true)仍能繼續運行!須要手動退出
break;
}
}
}
複製代碼
// Demo1.java的源碼
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
try {
int i=0;
while (!isInterrupted()) {
Thread.sleep(100); // 休眠100ms
i++;
System.out.println(Thread.currentThread().getName()+" ("+this.getState()+") loop " + i);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() +" ("+this.getState()+") catch InterruptedException.");
}
}
}
public class Demo1 {
public static void main(String[] args) {
try {
Thread t1 = new MyThread("t1"); // 新建「線程t1」
System.out.println(t1.getName() +" ("+t1.getState()+") is new.");
t1.start(); // 啓動「線程t1」
System.out.println(t1.getName() +" ("+t1.getState()+") is started.");
// 主線程休眠300ms,而後主線程給t1發「中斷」指令。
Thread.sleep(300);
t1.interrupt();
System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
// 主線程休眠300ms,而後查看t1的狀態。
Thread.sleep(300);
System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
複製代碼
//設置該線程的優先級
thread.setPriority(1);
複製代碼