Follow these steps to implement the example:
- Copy the MyThread, MyThreadFactory, and MyTask classes into the project. They were implemented in the Implementing the ThreadFactory interface to generate custom threads for the fork/join framework recipe. You are going to use them in this example.
- Implement the main class of the example by creating a class named Main with a main() method:
public class Main {
public static void main(String[] args) throws Exception {
- Create a new MyThreadFactory object named threadFactory:
MyThreadFactory threadFactory=new MyThreadFactory
("MyThreadFactory");
- Create a new Executor object using the newCachedThreadPool() method of the Executors class. Pass the factory object created earlier as a parameter. The new Executor object will use this factory to create the necessary threads, so it will execute MyThread threads:
ExecutorService executor=Executors.newCachedThreadPool
(threadFactory);
- Create a new Task object and send it to the executor using the submit() method:
MyTask task=new MyTask();
executor.submit(task);
- Shut down the executor using the shutdown() method:
executor.shutdown();
- Wait for the finalization of the executor using the awaitTermination() method:
executor.awaitTermination(1, TimeUnit.DAYS);
- Write a message to indicate the end of the program:
System.out.printf("Main: End of the program. ");