Javaでスレッドを定義する方法は何ですか?

Javaでスレッドを定義する方法は、次の2つがあります:

  1. Threadクラスを継承する:Threadクラスを継承したカスタムクラスを作成し、そのrun()メソッドをオーバーライドします。run()メソッド内でスレッドのタスクロジックを定義します。
public class MyThread extends Thread {
    public void run() {
        // 定义线程的任务逻辑
    }
}
  1. Runnableインタフェースを実装する: Runnableインタフェースを実装したクラスを作成し、そのrun()メソッドを実装します。その後、Threadオブジェクトを作成し、その実装クラスのインスタンスをThreadのコンストラクタにパラメータとして渡します。
public class MyRunnable implements Runnable {
    public void run() {
        // 定义线程的任务逻辑
    }
}

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

Both methods can be used to create threads, but the difference lies in that inheriting the Thread class can only inherit one class, while implementing the Runnable interface can implement multiple interfaces, therefore it is recommended to create threads using the method of implementing the Runnable interface.
両方の方法はスレッドを作成するために使用できますが、Threadクラスを継承する場合は1つのクラスのみを継承できますが、Runnableインターフェースを実装すると複数のインターフェースを実装できますので、スレッドを作成する際にはRunnableインターフェースを実装する方法をお勧めします。

bannerAds