How it works...

In this recipe, you implemented a custom MyThread class extending the Thread class. This class has three attributes to store the creation date, the start date of its execution, and the end date of its execution. Using the start date and end date attributes, you implemented the getExecutionTime() method that returns the total time the thread spent in executing its task. Finally, you overrode the toString() method to generate information about a thread.

Once you had your own thread class, you implemented a factory to create objects of that class by implementing the ThreadFactory interface. It's not mandatory to make use of the interface if you're going to use your factory as an independent object, but if you want to use this factory with other classes of the Java Concurrency API, you must construct your factory by implementing this interface. The ThreadFactory interface has only one method: the newThread() method. This method receives a Runnable object as a parameter and returns a Thread object to execute the Runnable object. In your case, you returned a MyThread object.

To check these two classes, you implemented the MyTask class that implemented the Runnable object. This is the task to be executed in threads managed by the MyThread object. A MyTask instance puts its execution thread to sleep for 2 seconds.

In the main method of the example, you created a MyThread object using a MyThreadFactory factory to execute a Task object. If you execute the program, you will see a message with the start date and the execution time of the thread executed.The following screenshot shows the output generated by this example:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.34.169