Home / java / Threads in Java

Threads in Java

We can define a thread in the 2 ways
1.by extending thread class
2.By implementing Runnable interface

Q) Thread Class
Methods: –
getName()
run()
getPriority()
Sleep()
isAlive()
Start()
join()

Q) Object class
All other classes are sub classes of object class; Object class is a super class of all other class.
Methods: –
void notify()
void notifyAll()
Object Clone()
Sting toString()
Boolean equals(Object object)
Void wait()
void finalize() v
oid wait(long milliseconds, int nanoseconds)

• If we write wait() and notify(),we have to keep the methods in synchronization(block or method).
• InterruptedException is compile time exception.
• IllegalMonitorException raised Why because wait() and notify() methods are not inside synchronized.Thats why we have to make synchronization.
• If we call yield.it is going to be runnable state.
• Current thread is going to be wait until t2 is completed.(t2.join()).
• Join(),sleep(),yield() available in the Thread class.
• Join() is not static method.
• Sleep() & yield() are static methods.
• If we override start() then start() will be executed just like a normal method call & no new thread will be created.
• Overloading of run() is possible,but thread class start() will always call no argument run() only.the other run() we have to call explicitly like a normal method call.

9.WHAT is the difference between t.start() & t.run()?
Ans:
 A new thread will be created by t.start().That thread is resposible to execute run().
 But in case of t.run() no thread will be created & run() will be executed just like a normal method call.
 Impotence of thread class start() is
Class thread
{
Start()
{
1.Register this thread with thread scheduler & perform other initialization activities.
2.run().
}}
 If we are not overriding run() method.then thread class run() will be executed which has emty implementation & hence we won’t get any output.

Note:Highly recommended to override run() to define our job.

9. what is producer and consumer problem in threads. how can you
implement it ?
Ans:

10.Explain about Thread Priority?
Ans:
• Every thread in Java has some priority but the range of thread priorities is “1 to 10”.
• Thread class defines the following constants to define some standard priorities
1. THREAD.MIN.PRIORITY 1
2. THREAD.NORM.PRIORITY 5
3. THREAD.MAX.PRIORITY 10
• Thread scheduler will use these priorities while allocating CPU
• If two threads having same priority then we can’t expect exact execution order,it depends on thread scheduler.
• Default priority for main thread is 5.But for all the remaining threads it will be inheriting from the parent.
• To get & set priority of thread.
Public final int getPriority().
Public final void setPriority(int p).

11.what are the yield,join,sleep methods?
Ans:
These methods to prevent the execution.
1.yield():
 yield method causes,To pause current executing thread for giving the chance to remaining waiting threads of same priority.
 If there are no waiting threads or all waiting threads have low priority then the same thread will continue it’s execution once again.-+
2.join():If thread t1 executes t2.join() then t1 thread will entered into wiating state untill t2 completes.then t1 will continue its execution
3.sleep():If a thread don’t want to perform any operation for a perticular amount of time.when we use this we should handle interrupted exception other wise we will get compile time error.
10. how can you produce deadlock using two threads.

11. What are the different exceptions related to threads.

12. what are the methods available in Thread class.
Ans:
Methods: –

getName() run()
getPriority() Sleep()
isAlive() Start()
join()

13. what are the methods available in Object class related to threads?
why wait,notify,notifyall methods are available in Object class.
Ans:
1. void notify() 2. void notifyAll() 3. Void wait()

 wait(),notify(),notifyall() available in object class.but not thread class. Becoz Threads are required to call these methods on any shared object (java.lang.object).

14. when IllegalMonitorStateException is going to occur ?
Ans:
IllegalMonitorException raised Why becoz wait() and notify() methods are not inside synchronized.Thats why we have to make synchronization.

15. differences b/w sleep and wait?
Ans:
• Sleep() is going to wait untill sometime.sleep(10000) is defenatly wait untill 5 seconds.
• Wait() is going to wait untill call notify().wait(30000) is not wait 30sec.it is defenatily wait when other person call notify() immediately come out.
16. wait method releases lock or not ? when thread is going to wait state?

17. Thread life cycle.

 Once we created a thread object then it is said to be in new state or born state.
 If we call start() method then the thread will be entered into ready or runnable state.
 If Threadscheduler allocates cpu,then the thread will entered intorunning state.
 If run() method completes then the thread will entered into deadstate.
18.how can you create deadlock?
Ans:If two threads are waiting for each other forever.Such type of situation is called “Deadlock”.
In case of deadlock waiting threads never end.
How to kill thread?
Ans:stop().
19.how to create Deamon thread?
Ans:
 The Threads which are executing in the background are called Daemon treads”
Ex:Garbagecollector
 Themain objective of Daemon threads is to provide support for non-daemon threads.
 t1.setDaemon(true).
 t1.start().
Output:created daemon thread
• T1.start()
• T1.setDaemon(true)
Output:IllegalTreadstateException
–We have to make Daemon after creating thread
–don’t do after starting thread.
package com.slokam.corejava;

publicclass ThreadTest {

publicstaticvoid main(String[] args) {
Data data = new Data();
Producer producer = new Producer(data);
Consumer consumder = new Consumer(data);

Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumder);
t1.setDaemon(true);
t1.getName();
producer.setT(t2);
t1.start();
t2.start();

}

}

class Data {
privateintdata;
privatebooleanavail=false;

synchronizedpublicvoidinsert(int data)
{
if(avail==true)
{
try {
wait(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

this.data=data;
avail=true;
notifyAll();

}

synchronizedpublicint using()
{
if(avail==false)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
avail=false;
notifyAll();
returnthis.data;
}

}

class Producer implements Runnable{

private Data data ;
private Thread t2;

publicvoid setT(Thread t) {
this.t2 = t;
}

public Producer(Data data)
{
this.data=data;
}
@Override
publicvoid run() {

for(int i=1;i<=20;i++) { data.insert(i); try { Thread.sleep(5000); //t2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Consumer implements Runnable{ Data data ; public Consumer(Data data) { this.data=data; } @Override publicvoid run() { for(int i=1;i<=20;i++) { System.out.println(data.using()); }}}

About Mohammad Fareed

Software Engineer @ Tekzenit.

Check Also

What is Mutable and Immutable ?

1.what is the Difference between String and StringBuffer? Ans: 1. The string is immutable whereas …

Leave a Reply

Your email address will not be published. Required fields are marked *