LoginSignup
1
1

More than 5 years have passed since last update.

【Java】新しいThreadの生成方法その②

Posted at

#①に続き

①が継承という方法のため、利用上色々不便がある。その替わりに、②の方法の方がスレッド生成する際に多く使われているだろう。

方法②: Runnableインターフェースを実装したクラスを利用してスレッドを作成する

ステップとしては:

・runnableインターフェースを実装したサブクラスを作成
・run()メソッドのオーバーライド
・作成したrunnableクラスのインスタンス化
・生成したrunnableインスタンスを引数に、Threadのコンストラクタで新しくThreadのインスタンスを生成する
・Threadのインスタンスでstart()メソッドを呼び出し

実際書いてみた:
public class ThreadTest2 implements Runnable{

@Override
public void run(){
    for (int i = 0; i < 5; i++){
        System.out.println("新規のスレッドから出力します");
    }
}

}

public class Sample2 {

public void main (String[] args){
    ThreadTest2 th1 = new ThreadTest2();
    Thread thread = new Thread(th1);
    thread.start();

}

}

ここでポイントとなるのが、
Thread thread = new Thread(th1);

上記のコードは、Threadクラスのコンストラクタを利用し、新しくスレッドを生成する方法である。
runnableインターフェースを実装したクラスを引数にすれば、新しくThreadクラスを生成することができる。

Thread(Runnable target)
新しい Thread オブジェクトを割り当てます。

Threadクラスが新しくできれば、残りは①と同じく、start()メソッドでスレッドを起動し、スケジューラに実行を任せるだけ。

1
1
2

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
1
1