1.線程的狀態
new Thread():線程被創建
線程可運行狀態,搶到cpu纔是真正的運行狀態
運行過程中cpu被搶/sleep()/wait()—-阻塞
結束—-線程自動運行完/推薦:標誌位
2.線程的常用方法
sleep():線程休眠(讓出cpu,不讓出鎖)
interrupt():打斷線程的sleep()/wait()…
join():等待線程終止
yield():暫停線程
setPriority():設置線程的優先級別
setName():設置名
isAlive():測試線程是否處於活動狀態
package thread;
/*
* 拋出InterruptedException異常
* 線程1:sleep()
* 線程2:打擾線程1
*/
public class Thread_4 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2(t1);
t1.start();
t2.start();
}
}
class MyThread1 extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("被打擾了");
e.printStackTrace();
}
}
}
class MyThread2 extends Thread{
private MyThread1 t1;
public MyThread2(MyThread1 t1){
super();
this.t1 = t1;
}
@Override
public void run() {
System.out.println("線程中斷");
t1.interrupt();
}
}