スレッドはひとつのプログラム内で複数の処理を同時並行的に実行するための仕組みで、スレッドの処理内容を書く際にラムダ式が使われることが多いです。
ここではJavaでスレッドを利用する方法について学びます。
まず最初にスレッドを作成します。
ラムダ式を使ってこのスレッド内で実行する処理内容を書きます。
var スレッド名 = new Thread( ()->{
処理内容
});
次に作成したスレッドを実行します。
するとスレッドがいま動いているプログラム(メインスレッド)とは別に並行して動き始めます。
スレッド名.start()
実行したスレッドの処理が終了するのを待ちたい時は次のように書きます。
スレッド名.join()
ではスレッドを使った例を示します。
次のソース1を実行するとスレッドが2つ(thread1とthread2)作られます。
thread1は0.1秒おきに"thread1"と表示します。
一方thread2は0.5秒おきに"thread2"と表示します。
import java.lang.Thread;
public class Main {
// msecだけ停止する関数
public static void sleep(int msec){
try{
Thread.sleep(msec);
}
catch(InterruptedException e){}
}
public static void main(String[] args){
var thread1 = new Thread( ()->{
for(var i = 0; i < 10; ++i ){
sleep(100);
System.out.println("thread1");
}
});
var thread2 = new Thread( ()->{
for(var i = 0; i < 2; ++i ){
sleep(500);
System.out.println("thread2");
}
});
// 各スレッドを実行
thread1.start();
thread2.start();
// 各スレッドが停止するまで待つ
try{
thread1.join();
thread2.join();
}
catch(InterruptedException e){}
}
}
結果は次のようになります。
2つのスレッドが並行して動いていることがわかります。
thread1 thread1 thread1 thread1 thread2 thread1 thread1 thread1 thread1 thread1 thread2 thread1