package learn.thread;
public class Demo1 {
public static String stemp = null;
public static void main(String[] args) {
// 獲取運行線程名稱
stemp = Thread.currentThread().getName();
System.out.println(stemp);
// 匿名內部類實現線程
Thread t1 = new Thread() {
@Override
public void run() {
try {
int count = 0;
while (count < 5) {
Thread.sleep(50);
System.out.println("我是t1線程");
count++;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取運行線程名稱
stemp = Thread.currentThread().getName();
System.out.println(stemp);
}
};
// 通過繼承線程類實現的線程
Task1 t2 = new Task1();
// 通過繼承線程接口實現線程
Task2 task2 = new Task2();
// 通過接口實現的話,要放到線程類裏才能啓動
Thread t3 = new Thread(task2);
// 啓動線程,啓動順序不等於運行順序
t1.start();
t2.start();
t3.start();
}
}
class Task1 extends Thread {
public static String stemp = null;
@Override
public void run() {
try {
int count = 0;
while (count < 5) {
Thread.sleep(50);
System.out.println("我是t2線程");
count++;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取運行線程名稱
stemp = Thread.currentThread().getName();
System.out.println(stemp);
}
}
class Task2 implements Runnable {
public static String stemp = null;
@Override
public void run() {
try {
int count = 0;
while (count < 5) {
Thread.sleep(50);
System.out.println("我是t3線程");
count++;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取運行線程名稱
stemp = Thread.currentThread().getName();
System.out.println(stemp);
}
}
java 多線程學習之創建線程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.