1、Thread类
2021-08-25 本文已影响0人
金石_832e
创建线程要注意三点:
- 1、继承Thread类
- 2、重写run方法
- 3、执行start方法
简单实现
public class TestThread1 extends Thread {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("run方法执行第" + i + "次");
}
}
public static void main(String[] args) {
TestThread1 testThread1 = new TestThread1();
// 注意调用的是start方法才开启线程,而不是run方法
testThread1.start();
for (int i = 1; i <= 200; i++) {
System.out.println("main方法执行第" + i + "次");
}
}
}
结果

两个方法同时抢占线程,谁抢到谁运行。线程开始并不一定立即执行,而是由CPU调度