Java中实现线程的两种方式

在Java中,线程是实现多任务的基本单位。线程的创建有两种方式,一种是继承Thread类,另一种是实现Runnable接口。下面我们将分别介绍这两种方式的实现方法及其代码示例。

继承Thread类

继承Thread类是一种创建线程的简单方式,只需继承Thread类并重写run()方法即可。下面是一个继承Thread类的示例代码:

public class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

在上面的示例中,我们定义了一个MyThread类,继承自Thread类,并重写了run()方法。在main方法中创建了一个MyThread对象并调用它的start()方法来启动线程。

实现Runnable接口

实现Runnable接口是另一种创建线程的方式,需要定义一个实现了Runnable接口的类,并实现其run()方法。下面是一个实现Runnable接口的示例代码:

public class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

在上面的示例中,我们定义了一个MyRunnable类,实现了Runnable接口,并重写了run()方法。在main方法中创建了一个MyRunnable对象,并将其作为参数传递给Thread类的构造方法,然后调用线程的start()方法来启动线程。

线程创建关系图

erDiagram
    THREAD <|-- MyThread : 继承
    THREAD <|-- MyRunnable : 实现

创建线程的流程图

flowchart TD
    A[开始] --> B{选择线程创建方式}
    B --> |继承Thread类| C[定义并启动线程]
    B --> |实现Runnable接口| D[定义并启动线程]
    C --> E[结束]
    D --> E

通过以上示例,我们可以看到在Java中实现线程有两种方式:继承Thread类和实现Runnable接口。根据具体需求选择适合的方式来创建线程,使得多任务处理更加灵活高效。希望本文对你有所帮助!