Java——继承Thread类创建多线程
单线程
因为该程序是一个单线程程序,所以只会循环run()方法的死循环。
单线程程序
public class ExampleM01 {
public static void main(String[] args) {
MyThread myThread =new MyThread(); //创建 MyThread 实例对象
myThread.run(); //调用 MyThread类的 run()方法
while (true) { //该循环是个死循环,打印输出语句
System.out.println("Main方法在运行");
}
}
}
class MyThread {
public void run() {
while (true) { //该循环是个死循环,打印输出语句
System.out.println("MyThread 类的 run()方法在运行");
}
}
}
多线程
JDK 中提供了一个线程类 Thread ,通过继承 Thread 类,并重写 Thread 类中的 run ()方法便可实现多线程。
在 Thread 类中,提供了一个 start()方法用于启动新线程,线程启动后,系统会自动调用 run()方法。
多线程程序
public class ExampleM02 {
public static void main(String[] args) {
MyThread02 myThread =new MyThread02(); //创建 MyThread 线程对象
myThread.start(); //开启线程
while (true) { //该循环是个死循环,打印输出语句
System.out.println("Main()方法在运行");
}
}
}
class MyThread02 extends Thread{
public void run() {
while (true) { //该循环是个死循环,打印输出语句
System.out.println("MyThread 类的 run()方法在运行");
}
}
}