Reputation: 502
I need to execute a piece of code independently of main thread, i have achieved this through
new Thread(()->{
someBigWork()
}).start();
This works fine, but i want to achieve this via Executors newSingleThreadExecutor
I have tried the following code
public static void main()
{
try{
// some my code should run in main Thread
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> someBigWork());
// some my code should run in main Thread
}catch(Expection e){
// some handeling code
}finally{
executorService.shutdown();
}
What i see is main thread exited only after someBigWork() execution completes.
I am running this code via cmd line, i have added some logs , after pring logs the program is exited (i am think , whether main Thread is waiting for someBigWork() to complete)
I want to run someBigWork() independently.
Am i missing something ?
Please correct me if im wrong
Upvotes: 0
Views: 944
Reputation: 21
The main thread in your code exits after someBigWork() just by chance. If you add Thread.sleep(delayInMilliseconds) into someBigWork() and logging with thread's name at the end of both main() and someBigWork()
System.out.println(Thread.currentThread().getName() + ": end of myMethodName()");
then you'll see that they run independently.
Upvotes: 1