Java Thread 类
Thread 类简介
对于线程的概念,本身是操作系统内核提出的概念。如果要执行并发编程,就需要掌握不同的系统 API(例如 Windows 系统 API、Linux 系统 API)等。不同系统的 API 是不一样的。
对于我们 Java 程序员来说,Java 的 API 早已封装好对应的系统 API,我们只需要学习 Java 的 API 即可。而进行并发编程的 Java 最重要的 API 就是标准库中的 Thread 类。通过这个类,我们可以实现对于线程的创建,以及利用每个线程进行业务逻辑和任务的执行。
Thread 是 java.lang 下面的一个库,是不需要手动导包的。
创建线程的方式
继承 Thread 类
代码示例
/**
* 创建线程:
* 继承 Thread
* 重写 run 方法
*/
public class MyThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println("MyThread 的 run 线程 正在运行...");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
// 创建一个线程
myThread.start();
// 主方法
while (true) {
System.out.println("main 线程 正在运行...");
Thread.sleep();
}
}
}


