LoginSignup
0
2

More than 5 years have passed since last update.

Java でスレッドを起動する方法2種類 +@

Last updated at Posted at 2017-11-03

Thread のサブクラス

Thread クラスを継承して run() メソッドを実装する。

public class Qiita {
    public static void main(String[] args) {
        new HelloThread("World!").start();
        new HelloThread("Qiita!").start();
    }
}

class HelloThread extends Thread {
    private String message;

    public HelloThread(String message) {
        this.message = message;
    }

    public void run() {
        System.out.print("Hello, " + message);
    }
}

Runnable インターフェース

Runnable インターフェースを実装したクラスを、Thread のコンストラクタに渡す。

public class Qiita {
    public static void main(String[] args) {
        new Thread(new Greeting("World!")).start();
        new Thread(new Greeting("Qiita!")).start();
    }
}

class Greeting implements Runnable {
    private String message;

    public Greeting(String message) {
        this.message = message;
    }

    public void run() {
        System.out.print("Hello, " + message);
    }
}

(+@) ThreadFactory でスレッドを生成する

ThreadFactory でスレッドの生成を抽象化する。

public class Qiita {
    public static void main(String[] args) {
        ThreadFactory factory = Executors.defaultThreadFactory();
        factory.newThread(new Greeting("Qiita!")).start();
    }
}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2