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 多线程学习之创建线程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.