メインのJavaプログラムからJavaスレッドを生成したいのですが、そのスレッドはメインプログラムに干渉することなく個別に実行する必要があります。あるべき姿は次のとおりです。
- ユーザーが開始したメインプログラム
- いくつかのビジネスは機能し、バックグラウンドプロセスを処理できる新しいスレッドを作成する必要があります
- スレッドが作成されるとすぐに、メインプログラムは、生成されたスレッドが完了するまで待機するべきではありません。実際、それはシームレスでなければなりません。
メインのJavaプログラムからJavaスレッドを生成したいのですが、そのスレッドはメインプログラムに干渉することなく個別に実行する必要があります。あるべき姿は次のとおりです。
簡単な方法の1つは、自分でスレッドを手動で生成することです。
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
runYourBackgroundTaskHere();
}
};
new Thread(r).start();
//this line will execute immediately, not waiting for your task to complete
}
または、複数のスレッドを生成する必要がある場合、またはそれを繰り返し実行する必要がある場合は、より高いレベルの同時APIとエグゼキューターサービスを使用できます。
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
runYourBackgroundTaskHere();
}
};
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(r);
// this line will execute immediately, not waiting for your task to complete
executor.shutDown(); // tell executor no more work is coming
// this line will also execute without waiting for the task to finish
}
これは、匿名の内部クラスを使用してスレッドを作成する別の方法です。
public class AnonThread {
public static void main(String[] args) {
System.out.println("Main thread");
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Inner Thread");
}
}).start();
}
}
また、Java 8の方法で実行したい場合は、次のように簡単に実行できます。
public class Java8Thread {
public static void main(String[] args) {
System.out.println("Main thread");
new Thread(this::myBackgroundTask).start();
}
private void myBackgroundTask() {
System.out.println("Inner Thread");
}
}
ラムダを使用すると、さらにシンプルになります!(Java 8)はい、これは実際に機能します。誰も言及していないことに驚いています。
new Thread(() -> {
//run background code here
}).start();