java thread - ghdrako/doc_snipets GitHub Wiki
Class Thread
Runnable taskl = () -> System.0ut.println(“This is task 1!");
Runnable task2 = () -> System.0ut.println(“This is task 2!");
Runnable task3 = () -> System.0ut.println(“This is task 3");
Thread threadl = new Thread(task1);
Thread thread2 = new Thread(task2);
Thread thread3 = new Thread(task3);
thread1.start();
thread2.start();
thread3.start();
When you call the thread constructor, java will go to the operating system (OS) and ask it to create an OS thread, because a thread in java is just a very thin wrapper around a system thread. Each time you call the thread constructor, the application will ask the operating system to create a thread. create such a thread is an expensive operation. The application needs to call the OS, and the OS in turn needs to create the system resoLu'ce and allocate some memory that the thread can use. The memory ofa thread lives off the heap, which means that the Iava virtual machine [IVM] can resize it. Once it is created, it can't be resized.
Executor Services
The executor service creates a pool ofthreads that you can submit tasks to. The benefit of this approach is that you don’t have to manage the reusing of threads yourself, but lava will do this for you. This way, the threads are only created once andwill be reused if the executor service is in scope.
Starting with Iava 21, the ExecutorService now implements the AutoCloseable interface. This means that it now implements the close method, and to exit the try-with-resource statement, all threads need to be finished either successfully or unsuccessfully.
Runnable taskl = () -> System.out.print1n("This is task 1!");
Runnable task2 = () -> System.out.print1n("This is task 2!");
Runnable task3 = () -> System.out.pIint1n("This is task 3!");
try(ExecutorService vte = Executors.newFixedThIeadPool(3)){
vte.submit(task1);
vte.submit(task2);
vte.submit(task3);
}