多线程之继承Thread类
-
多线程的创建,方式1,继承于Thread类
-
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 myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
//设置线程名称
myThread1.setName("线程A:");
myThread2.setName("线程B:");
//4.通过此对象调用start()方法
myThread1.start();
myThread2.start();
}
}