使用 继承 Thread 类的方式创建线程,在主线程中运行该线程,两个线程会随机交替运行。
定义一个线程类,该类继承 Thread 类,在线程中循环遍历 1 – 1000 所有数字。
定义 main 方法,启动该线程,然后再使用循环遍历 1–1000 所有数字。
MyThread 类:
public class MyThread extends Thread{
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
String name = Thread.currentThread().getName();
System.out.println(name + ":i = " + i);
}
}
}
测试类:
public class Test {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
MyThread mt = new MyThread("myThread");
mt.start();
for (int j = 0; j < 1000; j++) {
String name = Thread.currentThread().getName();
System.out.println(name + ":j = " + j);
}
}
}
运行结果如下图:
以上案例使用继承 Thread 类的方式定义线程类。