How to create a new Thread in java ?

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

  1. 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.

The output will be :

Now, let us assume you want to start multiple threads:

The output will be :

  1. 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.

The output will be:

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 🙂

原文链接:How to create a new Thread in java ?

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容