Thread

1.What is Thread ? Give methods of Thread class.
   
Thread is basically a lightweight sub-process, a smallest unit of processing. A thread have 
its own execution stack and program counter. Multithreading in java is a process of executing 
multiple threads simultaneously.

1. public void run(): is used to perform action for a thread. 
2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread. 
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease 
execution) for the specified number of milliseconds. 
4.public void join(): waits for a thread to die. 
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds. 
6. public int getPriority(): returns the priority of the thread. 
7. public int setPriority(int priority): changes the priority of the thread. 
8. public String getName(): returns the name of the thread. 
9. public void setName(String name): changes the name of the thread. 
10. public Thread currentThread(): returns the reference of currently executing thread. 
11. public int getId(): returns the id of the thread. 
12. public Thread.State getState(): returns the state of the thread. 
13. public boolean isAlive(): tests if the thread is alive. 
14. public void yield(): causes the currently executing thread object to temporarily pause and allow other 
threads to execute. 
15. public void suspend(): is used to suspend the thread(depricated). 
16. public void resume(): is used to resume the suspended thread(depricated). 
17. public void stop(): is used to stop the thread(depricated). 
18. public boolean isDaemon(): tests if the thread is a daemon thread. 
19. public void setDaemon(boolean b): marks the thread as daemon or user thread. 
20. public void interrupt(): interrupts the thread. 
21. public boolean isInterrupted(): tests if the thread has been interrupted. 
22. public static boolean interrupted(): tests if the current thread has been interrupted. 
Que. Give any Four Thread class Constructors. 
Ans. 
Thread( ) 
Thread (String name) 
Thread(Runnable r) 
Thread(Runnable r, String name)

Que. How can we create thread (or multiple threads) in java ? 

Ans. We can create thread by creating object of Thread class. Two ways in which this can be 
done: 
1) By implement the Runnable interface. 
2) By extend the Thread class. 
To implement Runnable, a class need only implement a single method called run( ). 
 public void run( ) 
Inside run( ), we can write the code which executed by the new thread. 
A class that implements Runnable have to create object of Thread class. 
We can use one of the following constructors of Thread class in the concept of implement 
Runnable interface. 
 Thread(Runnable threadOb); 
 Thread(Runnable threadOb, String threadName); 
After creating object of Thread, we can call start( ) method which call to run( ) method to 
execute the thread. (Prof. Viral S. Patel) 
Example : 
class MyThread implements Runnable
 Thread t; 
 
 MyThread(String threadName) 
 { 
 t = new Thread(this,threadName); 
 t.start(); 
 } 
 public void run() 
 { 
 ….. 
 } 
}
class Demo 
 public static void main(String args[]) 
 { 
 MyThread t1 = new MyThread(“Child1”); 
 MyThread t2 = new MyThread(“Child2”); 
 } 
The second way to create a new class that extends Thread class and then create an object of 
that class. The extending class must override the run( ) method. 
class MyThread extends Thread
 MyThread(String threadName) 
 { 
 super(threadName); 
 start(); 
 } 
 public void run() 
 { 
 ….. 
 } 
}
class Demo 
 public static void main(String args[]) 
 { 
 MyThread t1 = new MyThread(“Child1”); 
 MyThread t2 = new MyThread(“Child2”); 
 } 
Note : super call to Thread class’s constructor 
which is Thread(String threadName);

Que. Which methods are inherited in Thread class from class java.lang.Object ? 

Ans. equals, finalize, notify, notifyAll, wait methods are inherited in Thread class from class 
 java.lang.Object 
Que. Explain LifeCycle of Thread. 
Ans. A thread can be in one of the five states. According to sun, there is only 4 states in thread 
life cycle in java new, runnable, non-runnable and terminated. There is no running state. 
But for better understanding the threads, we are generally explaining it in the 5 states. The life 
cycle of the thread in java is controlled by JVM. The java thread states are as follows: 
1. New 
2. Runnable (ready-to-run) 
3. Running 
4. Non-Runnable (Blocked,Wait,Sleep) 
5. Terminated (Dead)

1) New 
The thread is in new state if you create an instance of Thread class but before the 
invocation of start() method. (Prof. Viral S. Patel) 
2) Runnable 
The thread is in runnable state after invocation of start() method, but the thread scheduler 
has not selected it to be the running thread. 
yield() is used to give the other threads of the same priority a chance to execute i.e. 
causes current running thread to move to runnable state. 
notify(): This wakes up threads that called wait() on the same object and moves the 
thread to ready state. 
notifyAll(): This wakes up all the threads that called wait() on the same object.

3) Running 
The thread is in running state if the thread scheduler has selected it. 
4) Non-Runnable (Blocked) 
This is the state when the thread is still alive, but is currently not eligible to run. 
When wait() method is invoked on an object, the thread executing that code gives up 
its lock on the object immediately and moves the thread to the wait state. 
sleep() is used to pause a thread for a specified period of time 
5) Terminated 
A thread is in terminated or dead state when its run() method exits 
Que. Explain Synchronization in Multithreading. 
Ans. 
 If process (or method) is Asynchronous then it does not guarantee thread-safety. As resource 
inside the asynchronous method accessed by multiple threads can be brought in inconsistent 
state. (Prof. Viral S. Patel) 
When two or more threads need access to a shared resource, they need some way to ensure 
that the resource will be used by only one thread at a time. The process by which this is achieved 
is called synchronization. 
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is 
an object that is used as a mutually exclusive lock, or mutex. 
As long as the thread holds the monitor, no other thread can enter the synchronized section of 
code. other threads are said to be waiting for the monitor. 
In java ‘synchronized’ keyword is used with the method to enter the thread in monitor.
It is also possible to mark a block of code as synchronized . 
synchronized void method( ) 
 ………. // code here is synchronized 
synchronized ( lock-object) 
 …………. //code here is synchronized 
Example of Synchronization using synchronized method and synchronized block: 
class MyResource 
synchronized void useRes() 
 { 
 System.out.print("["); 
 try 
 { 
 Thread.sleep(1000); 
 } 
 catch(Exception e) 
 { 
 } 
 
 System.out.print("]"); 
 } 
class MyThread implements 
Runnable 
 Thread t; 
 MyResource res; 
 MyThread(MyResource r) 
 { 
 res = r; 
 t = new Thread(this); 
 t.start(); 
 } 
 public void run() 
 { 
 res.useRes(); 
 } 
class Demo 
 public static void main(String args[]) 
 { 
 MyResource ob = new MyResource(); 
 MyThread t1 = new MyThread(ob); 
 MyThread t2 = new MyThread(ob); 
 } 
Output: 
[ ] [ ] 
Note: If we not write synchronized 
keyword before void users() method then 
output will be [[]].

class MyResource 
 void useResource() 
 { 
 System.out.print("["); 
 try 
 { 
 Thread.sleep(1000); 
 } 
 catch(Exception e) 
 { 
 } 
 
 System.out.print("]"); 
 } 
class MyThread implements 
Runnable 
 Thread t; 
 MyResource res; 
 MyThread(MyResource r) 
 { 
 res = r; 
 t = new Thread(this); 
 t.start(); 
 } 
 public void run() 
 { 
 synchronized(res) 
 { 
 res.useResource(); 
 } 
 } 
class Demo 
 public static void main(String args[]) 
 { 
 MyResource ob = new MyResource(); 
 MyThread t1 = new MyThread(ob); 
 MyThread t2 = new MyThread(ob); 
 } 
Output: 
[ ] [ ]

Whenever a thread has completed its work of using synchronized method (or block of code), it 
will hand over the monitor to the next thread that is ready to use the same resource. 
A Java multithreaded program may suffer from the deadlock condition because the 
synchronized keyword, when a thread is waiting for an object lock, that is acquired by another 
thread and second thread is waiting for an object lock that is acquired by first thread. Since, both 
threads are waiting for each other to release the lock, the condition is called deadlock. 

Que. Explain Deadlock in java. 

Ans. profresting situation may occur when two or more 
threads are waiting to gain control of a resource of each 
other. A Java multithreaded program may suffer from the 
deadlock condition because the synchronized keyword, 
when a thread is waiting for an object lock, that is acquired 
by another thread and second thread is waiting for an 
object lock that is acquired by first thread. 
Since, both threads are waiting for each other to release the 
lock, the condition is called deadlock.
 
We can see deadlock in synchronized method concept. 
Thread A 
….. 
resource1.method1(resource2); // hold resource1 
….. 
synchronized void method1(resource2) 
 ………… 
 try { Thread.sleep(100);} catch (Exception e) {} 
 resource2.function2( ); // need resource2 
 ………… 
synchronized void method2( ) 
….. 
Thread B 
……. 
resource2.function1( resource1); //hold resource2 
….. 
synchronized void function1(resource1) 
 ………... 
 try { Thread.sleep(100);} catch (Exception e) {} 
 resource1.method2( ); // need resource1 
 ………… 
synchronized void function2( ) 
….. 
}

We can also see deadlock in synchronized block concept. Example : 
Thread A 
….. 
synchronized(resource1) 
 …………… 
 try { Thread.sleep(100);} catch (Exception e) {} 
 synchronized(resource2) 
 { 
 ………… 
 } 
….. 
Thread B 
….. 
synchronized method1(resource2) 
 ……….. 
 try { Thread.sleep(100);} catch (Exception e) {} 
 synchronized method2(resource1) 
 { 
 ………….. 
 } 
….. 
Example of Deadlock : (Prof. Viral S. Patel) 
class Res1 
 synchronized void task1(Res2 r2) 
 { 
 System.out.print("["); 
 try 
 { 
 Thread.sleep(1000); 
 } 
 catch(Exception e) 
 { 
 } 
 r2.fun2(); 
 System.out.print("]"); 
 } 
 synchronized void task2() 
 { 
 System.out.println("tast2 of Res1"); 
 } 
class Res2 
 synchronized void fun1(Res1 r1) 
 { 
 System.out.print("("); 
 Try 
 { 
 Thread.sleep(1000); 
 } 
 catch(Exception e) 
 { 
 } 
 r1.task2(); 
 System.out.print(")"); 
 } 
 synchronized void fun2() 
 { 
 System.out.println("fun2 of Res2"); 
 } 
class MyThread implements Runnable 
 Thread t; 
 Res1 re1; 
 Res2 re2; 
 MyThread(Res1 r1, Res2 r2) 
 { 
 re1 = r1; re2 = r2; 
 t = new Thread(this); 
 t.start(); 
 } 
 public void run() 
 { 
 if(t.getName().equals("Thread-0")) 
 re1.task1(re2); //Thread-0 hold re1 & need re2
 else 
 re2.fun1(re1); //Thread-1 hold re2 & need re1 
 } 
class Demo 
 public static void main(String args[]) 
 { 
 Res1 ob1 = new Res1(); 
 Res2 ob2 = new Res2(); 
 MyThread t1 = new MyThread(ob1,ob2); 
 MyThread t2 = new MyThread(ob1,ob2); 
 } 
Output: 
[( 
Note : Thread-0 hold re1 and need re2 to 
complete its task1. Same as other side 
Thread-1 hold res2 and need res1 to 
complete its fun1. So deadlock generate 
after display [(.

Que. How mutex can be achieved in thread ? 

Ans. Mutex in thread at a time only one thread lock the particular region of code. If another 
thread want to lock the same region of code it must have to wait until first lock release. This can 
be achieved by java synchronized method or synchronized block. 

Que. Write down the use of volatile keyword. 

Ans.Volatile is used to indicate that a variable’s value will be 
modified by different threads and achieving synchronization in 
java in some cases, like visibility. Without volatile keyword 
different reader thread may see different values as compiler re-
order the code, free to cache value instead of always reading from 
main memory. So volatile keyword in java guarantees that value 
of the volatile variable will always be read from main memory 
and not from Thread’s local cache.

Que. Explain Inter-Thread Communication. 
Ans. Inter-thread communication can be defined as the exchange of messages between two or 
more threads. The transfer of messages takes place before or after the change of state of thread. 
For example, an active thread may notify to another suspended thread just before switching to 
the suspend state. Java implements inter-thread communication with the help of following three 
methods : 
final void wait( ) throws InterruptedException 
final void notify( ) 
final void notifyAll( ) 
wait() : Tells the calling thread to give up the monitor and Sends the calling thread into the sleep 
mode. This thread can now be activated only by notify or notifyall() methods. 
 One can also specify the time for which the thread has to wait. The desired waiting time 
period is specified as an argument to the wait() method. 
notify() : Resumes the first thread that went into the sleep mode. 
notifyall() : Resumes all the threads that are in sleep mode. The execution of these threads 
happens as per priority. (Prof. Viral S. Patel) 
 These methods are declared within Object class. Since the methods are declared as final they 
can not be overridden. 
class MyResource 
 int n; 
 boolean valueSet = false; 
 synchronized void put(int n) 
 { 
 if(valueSet) 
 try { wait(); } catch(Exception e){…} 
 this.n = n;GUAGE
 valueSet = true; 
 System.out.println("Put: " + n); 
 notify(); 
 } 
 synchronized void get() 
 { 
 if(!valueSet) 
 try { wait(); } catch(Exception e){…} 
 System.out.println("Got: " + n); 
 valueSet = false; 
 notify(); 
 } 
class Producer implements Runnable 
 MyResource res; 
 Thread t; 
 Producer(MyResource r) 
 { 
 res = r; 
 t = new Thread(this, "Producer"); 
 t.start(); 
 } 
 public void run() 
 { 
 for(int i=0;i<3;i++) 
 { 
 res.put(i*2); 
 } 
 } 
class Consumer implements Runnable 
 MyResource res; 
 Thread t; 
 Consumer(MyResource r) 
 { 
 res = r; 
 t = new Thread(this, "Consumer"); 
 t.start(); 
 } 
 public void run() 
 { 
 for(int i=0;i<3;i++) 
 { 
 res.get(); 
 } 
 } 
class PCFixed 
 public static void main(String args[]) 
 { 
 MyResource ob = new MyResource(); 
 new Producer(ob); 
 new Consumer(ob); 
 } 
Output : 
Put: 0 
Got: 0 
Put: 2 
Got: 2 
Put: 4 
Got: 4 

Que. Explain join( ) and isAlive( ) methods in Thread concept. 

Ans. Two ways exist to determine whether a thread has finished. 
First, we can call isAlive( ) on the thread. This method is defined by Thread, and its general form 
is : 
 final boolean isAlive( ) 
The isAlive( ) method returns true if the thread upon which it is called is still running.
It returns false otherwise. 
While isAlive( ) is occasionally useful, the method that you will more commonly 
use to wait for a thread to finish is called join( ), shown here: 
 final void join( ) throws InterruptedException 
This method waits until the thread on which it is called terminates. (Prof. Viral S. Patel) 
Additional forms of join( ) allow you to specify a maximum amount of time that you want to 
wait for the specified thread to terminate. 
 final void join(long miliseconds) throws InterruptedException 
class MyThread implements Runnable 
 Thread t; 
 MyThread(String tnam) 
 { 
 t = new Thread(this,tnam); 
 t.start(); 
 } 
 public void run() 
 { 
 for(int i=0;i<3;i++) 
 { 
 System.out.println(t.getName()+":"+i); 
 } 
 } 
Output : 
main start 
c1 isAlive :true 
c2 isAlive :true 
c1:0 
c2:0 
c1:1 
c2:1 
c1:2 
c2:2 
c1 isAlive :false 
c2 isAlive :false 
main exit 
class Demo 
 public static void main(String args[]) 
 { 
 System.out.println("main Start"); 
 MyThread t1 = new MyThread("c1"); 
 MyThread t2 = new MyThread("c2"); 
 
 System.out.println("c1 isAlive :" + t1.t.isAlive()); 
 System.out.println("c2 isALive :" + t2.t.isAlive()); 
 try 
 { 
 t1.t.join(); 
 t2.t.join(); 
 } 
 catch(InterruptedException e) 
 { 
 System.out.println(“Error caught”); 
 } 
 
 System.out.println("c1 isAlive :" + t1.t.isAlive()); 
 System.out.println("c2 isALive :" + t2.t.isAlive()); 
 System.out.println("main exit"); 
 } 
Note: we can see c1 and c2 thread exit before main 
thread exit. main wait until c1 and c2 complete their 
task because threads c1 and c2 call to join( ) method 
in main thread.









Comments