Java

java实现多线程有哪两种途径,区别是什么

小亿
145
2024-02-07 17:03:15
栏目: 编程语言

Java实现多线程有两种途径:继承Thread类和实现Runnable接口。

  1. 继承Thread类:创建一个继承自Thread类的子类,重写run()方法,并在其中定义线程的任务。通过创建该子类的对象,调用start()方法来启动线程。这种方式简单直观,但由于Java不支持多重继承,因此如果继承Thread类,就无法继承其他类。

示例代码如下:

public class MyThread extends Thread {
    @Override
    public void run() {
        // 线程的任务
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
  1. 实现Runnable接口:创建一个实现了Runnable接口的类,重写run()方法,并在其中定义线程的任务。通过创建该类的对象,再通过Thread类的构造方法将该对象作为参数传递进去,最后调用start()方法来启动线程。这种方式可以避免Java单继承的限制,且实现了接口的类可以被其他类继承或作为参数传递。

示例代码如下:

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程的任务
    }

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

区别:

0
看了该问题的人还看了