Javaでスレッド内のスレッドを起動します

user1409534:

私は、スレッドプールを持っていると私は名前のスレッドを持つスレッドプールからタスクを実行するだと言うthread-aの中に今thread-aそれを呼び出す私は新しいスレッドを始めていることができますthread-child。この手段ません(スレッドをプールし、かもしれない可能性があります)thread-aに戻って起こっているのスレッドプールthread-child走ら?またはthread-a死ぬために起こっていますか?

DKB:

:これは、実際の答えですhttps://stackoverflow.com/a/56766009/2987755
ただ、それに加えて、コードを追加します。

ExecutorService executorService = Executors.newCachedThreadPool();
Callable parentThread = () -> {
    System.out.println("In parentThread : " + Thread.currentThread().getName());
    Callable childThread = () -> {
        System.out.println("In childThread : " + 
        Thread.currentThread().getName());
        Thread.sleep(5000); // just to make sure, child thread outlive parent thread
        System.out.println("End of task for child thread");
        return 2; //ignore, no use here
    };
    executorService.submit(childThread);
    System.out.println("End of task for parent thread");
    return 1; //ignore, no use here
};
executorService.submit(parentThread);
Thread.sleep(8000); // wait until child thread completes its execution.
executorService.shutdown();

出力:

In parentThread : pool-1-thread-1
End of task for parent thread
In childThread : pool-1-thread-2
End of task for child thread

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=336298&siteId=1