Multiple tasks need to be executed simultaneously within a single application. The Java platform provides support for concurrent programming. To understand concurrent programming, you have to understand two things: process and thread.
A process has a self-contained execution environment, whereas threads exist within a process. Threads are known as lightweight processes.
Note that creating a new thread requires fewer resources than creating a new process. Basically, threads share resources of the process, in which they exist.
There are two different ways to create threads:
- 1. Extending
Thread
class - 2. Implementing
Runnable
interface
Inheriting Thread class
Here, we are defining a class inheriting the Thread
class. The Thread
class defines a method run
, which does nothing. This method needs to be overwritten in our class as this method should contain the code of the thread.
A.java
Main.java
Implementing Runnable interface
Here, we are defining a thread by implementing the Runnable
interface. Again in this class, we have to define the run
method, which will contain the code of the thread.
B.java
Main.java
Thread join
In the above examples, you will see that the main thread is exiting before the completion of the child threads. If the main thread needs to be alive until all the threads are terminated, the threads are to be joined with the main thread as shown below.
Main.java
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.