实现步骤:
1: 创建Thread类的子类。
2: 重写Thread类的run()方法。
3: 创建Thread子类的对象。
4: 子类对象调用start()方法。
代码实现:
/**
* 遍历100以内的偶数
*/
//1: 创建Thread类的子类
class MyThread extends Thread {
//2: 重写Thread类的run()方法
@Override
public void run() {
for (int i=0; i<100; i++) {
if (i % 2 == 0) {
System.out.println("线程名: "+Thread.currentThread().getName()+"********"+i);
}
}
}
}
public class ThreadTest {
public static void main(String[] args) {
//3: 创建Thread子类的对象
MyThread thread = new MyThread();
//4: 子类对象调用start()方法:1⃣️启动当前线程。2⃣️调用当前线程的run方法(子类MyThread中重写的run方法)
thread.start();
}
}