We are going to explore different ways to start a thread & execute parallel tasks.
This is very useful, in particular when dealing with the long or recurring operations that can’t run on the main thread or where the UI interaction can’t be put on hold while waiting for results or response.
Running a Thread
- By Extending the Thread class
Define the task class which will perform a task on different thread. The class should extends Thread class & override the run method to define the task to execute on a separate thread.
And now we write a second class to initialize and start our thread:
We should call the start() method on threads in the NEW state (the equivalent of not started). Otherwise, Java will throw an instance of IllegalThreadStateException exception.
Now, let us assume you want to start multiple threads:
- Implementing the Runnable Interface
Define a class which will implements the Runnable Interface. The Runnable interface is also a functional interface, which has only 1 method i.e run.
If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitely create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute.
Thanks 🙂
keep-learning 🙂
暂无评论内容