As we know that there are two ways to create a thread:
1. By extending Thread class
2. By Runnable interface
Today we will discuss how to create a thread with the help of Runnable interface. Runnable is an interface which includes run() method, where we can implement our code as a Thread. To understand how the Runnable interface can be used, let us simplify the concept through an example:
class A
{
public void run()
{
for (int i = 1; i <= 5; i++)
{
System.out.println(“From class A :” + i);
}
}
}
class run
{
public static void main (String args[])
{
A aobj = new A();
Thread t1 = new Thread(aobj);
t1.start();
}
}
Output:
Explanation:
Runnable is an interface, so we need to inherit the method run() through implements keyword. After declaring this statement, run() method is now referred as the part of class A. run() is a method that is already declared in Runnable interface, just we have to redefine in class A and we can use all the facilities of run() method. Now, the main essential part is how to declare an object of the Runnable interface. To perform this task:
1. First and foremost, create the object of class A as we have seen while extending the Thread class.
2. Now to call run() method, we can’t call directly with the object of class A, so we have to create object of the Thread class and then we will assign that to object of the Thread class. Here, we have taken aobj as an object for A class and t1 for Thread class. It is same as
a = b
b = c
3. Now we have finished the task of creating the objects, we can call the method by using t1.start() statement.
Synchronization
When two or more threads need to use shared resources at that time, they need some way to ensure that the resources will be used by only one thread at a time. This process is known as synchronization.
When the thread begins executing a synchronize method, it automatically acquires a lock on the object. A lock is automatically relinquished when the method is completed. Whenever a thread had completed its work of using synchronized method (or block of code), it will hand over the lock to the next thread that is ready to use the same resource.
For example, assume that the thread A must access Method1 before it can release Method2, but the thread B cannot release Method1 until it gets hold of Method2. Because these are mutually exclusive conditions, a deadlock occurs. The code below illustrates this:
Thread A
synchronized method2()
{
synchronized method1()
{
……………………………..
………………………………
}
}
Thread B
synchronized method1()
{
synchronized method2()
{
……………………………..
………………………………
}
}
Made By: Chaudhary Amit V.

Comments
Post a Comment