logo

Java でのマルチスレッド化

マルチスレッドは、CPU を最大限に活用するためにプログラムの 2 つ以上の部分を同時に実行できるようにする Java 機能です。このようなプログラムの各部分はスレッドと呼ばれます。したがって、スレッドはプロセス内の軽量プロセスです。

スレッドは 2 つのメカニズムを使用して作成できます。

  1. Threadクラスの拡張
  2. 実行可能インターフェイスの実装

Threadクラスを拡張してスレッドを作成する
を拡張するクラスを作成します。 java.lang.スレッド クラス。このクラスは、Thread クラスで使用可能な run() メソッドをオーバーライドします。スレッドは run() メソッド内でその動作を開始します。新しいクラスのオブジェクトを作成し、start() メソッドを呼び出してスレッドの実行を開始します。 Start() は、Thread オブジェクトの run() メソッドを呼び出します。



ジャワ




// Java code for thread creation by extending> // the Thread class> class> MultithreadingDemo>extends> Thread {> >public> void> run()> >{> >try> {> >// Displaying the thread that is running> >System.out.println(> >'Thread '> + Thread.currentThread().getId()> >+>' is running'>);> >}> >catch> (Exception e) {> >// Throwing an exception> >System.out.println(>'Exception is caught'>);> >}> >}> }> // Main Class> public> class> Multithread {> >public> static> void> main(String[] args)> >{> >int> n =>8>;>// Number of threads> >for> (>int> i =>0>; i MultithreadingDemo object = new MultithreadingDemo(); object.start(); } } }>

2つの文字列の違いPython
>

>

出力

Thread 15 is running Thread 14 is running Thread 16 is running Thread 12 is running Thread 11 is running Thread 13 is running Thread 18 is running Thread 17 is running>

Runnable Interfaceの実装によるスレッドの作成
java.lang.Runnable インターフェースを実装し、run() メソッドをオーバーライドする新しいクラスを作成します。次に、Thread オブジェクトをインスタンス化し、このオブジェクトの start() メソッドを呼び出します。

ジャワ




// Java code for thread creation by implementing> // the Runnable Interface> class> MultithreadingDemo>implements> Runnable {> >public> void> run()> >{> >try> {> >// Displaying the thread that is running> >System.out.println(> >'Thread '> + Thread.currentThread().getId()> >+>' is running'>);> >}> >catch> (Exception e) {> >// Throwing an exception> >System.out.println(>'Exception is caught'>);> >}> >}> }> // Main Class> class> Multithread {> >public> static> void> main(String[] args)> >{> >int> n =>8>;>// Number of threads> >for> (>int> i =>0>; i Thread object = new Thread(new MultithreadingDemo()); object.start(); } } }>

>

>

出力

Thread 13 is running Thread 11 is running Thread 12 is running Thread 15 is running Thread 14 is running Thread 18 is running Thread 17 is running Thread 16 is running>

スレッドクラスと実行可能インターフェイス

  1. Thread クラスを拡張する場合、Java は多重継承をサポートしていないため、このクラスは他のクラスを拡張できません。ただし、Runnable インターフェイスを実装した場合でも、クラスは他の基本クラスを拡張できます。
  2. Thread クラスを拡張することでスレッドの基本機能を実現できます。これは、Runnable インターフェイスでは利用できない、yield()、interrupt() などのいくつかの組み込みメソッドが提供されるためです。
  3. runnable を使用すると、複数のスレッド間で共有できるオブジェクトが得られます。