Multithreading is a programming ability to perform multiple process in parallel based on time-sharing technique. Java allows writing programs that allow multi-threading. Creating threads in java is simple. Threads are implemented in the form of objects that contain a method called run(). The run() method is the heart of any thread. It is the only method in which the thread’s behavior can be implemented. The run() method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initiating it with the help of another method called start ( ).
In java, we can create threads in two different ways.
1. By extending Thread class: Here, we create a thread class that extends Thread class and override its run() method with the code required by the thread. This gives us access to all the thread methods directly. It includes the following steps:
1. Declare the class as extending the Thread class.
2. Override the run( ) method that defines the task of the thread
3. Create a thread object and call the start( ) method to initiate the thread execution.
Now, the program looks something like this:
class MyThread extends Thread
{
...
public void run ( )
{
... // thread code
}
}
class Test
{
public static void main(String as[])
{
MyThread t1 = new MyThread();
t1.start();
}
}
More on This: Creating a Thread by extending Thread Class
2. By implementing Runnable interface: Here, we define a class that implements Runnable interface. The Runnable interface has only one method, run( ), that is to be implemented by the class. This procedure becomes mandatory when the class already extends another class and to be made as a thread. It includes the following steps:
1. Declare a class that implements Runnable interface.
2. Implement the run( ) method.
3. Create a thread by defining an object that is instantiated from this "runnable" class or create it within that class.
4. Call the thread's start( ) method to run the thread.
Now, the program looks something like this:
class MyThread implements Runnable
{
Thread t;
MyThread( )
{
t= new Thread(this);
}
public void run ( )
{
... // thread code
}
}
class Test
{
public static void main(String as[])
{
MyThread t1 = new MyThread();
t1.t.start();
}
}
More on This: Creating a Thread Using Runnable Interface
0 comments:
Post a Comment