多线程的实现有3种途径:
继承Thread类实现多线程有3步:自定义线程类继承Thread类 --> 重写run()方法 --> 调用start()方法启动线程
调用run()方法执行完才继续执行下一步,调用start()方法才是并行交替执行。
package com.happy.thread;
public class TestThread1 extends Thread {
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 2000; i++) {
System.out.println("我在看代码--"+i);
}
}
//主线程
public static void main(String[] args) {
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 2000; i++) {
System.out.println("我在学习--"+i);
}
}
}
部分运行结果:
原文:https://www.cnblogs.com/happy-lin/p/14958205.html