一. 继承 Thread 类创建线程
- 可以通过 getId getName 方法获得线程 “ID” 和 “线程名”
- 使用继承 Thread 类的方式来创建线程时, 多个线程之间无法共享线程类的实例变量
public class MyThread extends Thread{
@Override
public void run() {
for(int i = 0; i < 10; ++i){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i + ": 线程ID: "+ getId() + " 线程名: " + getName());
}
}
}
public static void thread(){
//Thread 方式创建
MyThread thread = new MyThread("线程名");
thread.start();
}
二. 实现 Runnable 接口创建线程
- 只能通过 Thread.currentThread().getName() Thread.currentThread.getId() 获取线程 “ID” 和 “线程名”
public class MyRunnable implements Runnable {
@Override
public void run() {
for(