package cn.itcast.heima2;
public class TraditionalThread {
/**
* @param args
*/
public static void main(String[] args) {
Thread thread = new Thread(){
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1:" + Thread.currentThread().getName());
System.out.println("2:" + this.getName());
}
}
};
thread.start();
Thread thread2 = new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1:" + Thread.currentThread().getName());
}
}
});
thread2.start();
new Thread(
new Runnable(){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable :" + Thread.currentThread().getName());
}
}
}
){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread :" + Thread.currentThread().getName());
}
}
}.start();
}
}
JUC線程-傳統線程回顧
創建線程的兩種傳統方式
在Thread子類覆蓋的run方法中編寫運行代碼
•涉及一個以往知識點:能否在run方法聲明上拋出InterruptedException異常,以便省略run方法內部對Thread.sleep()語句的try…catch處理?
在傳遞給Thread對象的Runnable對象的run方法中編寫代碼
總結:查看Thread類的run()方法的源代碼,可以看到其實這兩種方式都是在調用Thread對象的run方法,如果Thread類的run方法沒有被覆蓋,並且爲該Thread對象設置了一個Runnable對象,該run方法會調用Runnable對象的run方法。
問題:如果在Thread子類覆蓋的run方法中編寫了運行代碼,也爲Thread子類對象傳遞了一個Runnable對象,那麼,線程運行時的執行代碼是子類的run方法的代碼?還是Runnable對象的run方法的代碼?
•涉及到的一個以往知識點:匿名內部類對象的構造方法如何調用父類的非默認構造方法。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.