You are on page 1of 9

interrupting a thread

If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt()
method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the
thread is not in the sleeping or waiting state, calling the interrupt() method performs normal
behaviour and doesn't interrupt the thread.

we can interrupt a sleeping or waiting thread by using interrupt( ) method of thread class.

public void interrupt()

when ever we are calling interrupt() the target thread may not be effected immediately. At the time
of calling interrupt if the target thread is not in sleeping or in waiting state interrupt call will wait
until target thread entered into sleeping or waiting state the interrupt call will impact the target
thread..

Ex:
class MyThread extends Thread

public void run()

try

for(int i=0;i<100;i++)

System.out.println("lazy thread");

Thread.sleep(5000);

catch(InterruptedException e)

System.out.println(" i got interrupted");

}
}

class InterruptDemo

public static void main(String args[])

MyThread t=new MyThread();

t.start();

t.interrupt();//------------(1)

System.out.println("end of main method");

If we are commenting line 1 then main thread wont interrupt child thread hence both threads will be
executed until completion.

If we are not commenting line 1 then main thread interrupts the child thread rises
InterruptedException.

In this case the o/p is :

Synchronization

‘synchronized’ is the keyword applicable for the methods and blocks. We can’t apply this keyword
for variables and classes.

If a method declared as synchronized at a time only one thread is allowed to execute that method on
the given object. The main advantage of synchronized keyword is we can overcome data
inconsistency problem. The main limitation of synchronized keyword is it increases the waiting time
of a thread, and effects the performance of the system.

Hence if there is no specific requirement it’s not recommended to use synchronized keyword.

Every object in java has a unique lock.


Synchronization concept internally implemented by using this lock concept. Whenever we are using
synchronized keyword then object level lock concept will come into picture.
If a thread want to execute any synchronized method on the object first it should require the lock of
that object. Once a thread got the lock then it is allowed to execute any synchronized method on that
object.
Once synchronized method completes then automatically the lock will be released

While a thread executing a synchronized method on the object, then the remaining threads are not
allowed to execute any synchronized method on the same object. But the remaining threads are
allowed to execute any non-synchronized method on the same object.

Every object in java has unique lock but a thread can acquire more than one lock at a time.

Ex:
class Display
{
public synchronized void wish(String name)
{
for(int i =0;i<10;i++)
{
System.out.print("Hai.......!");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
}
System.out.println(name);
}
}
}
class MyThread extends Thread
{
Display d;
String name;
MyThread(Display d,String name)
{
this.d = d;
this.name = name;
}
public void run()
{
d.wish(name);
}
}
class SynchronizedDemo
{
public static void main(String arg[])
{
Display d = new Display();
MyThread t1 = new MyThread(d," Dhoni ");
MyThread t2 = new MyThread(d," Yuvraj ");
t1.start();
t2.start();
}
}
If we are not declaring wish method as “synchronized” we will get irregular o/p because both threads
will execute simultaneously. If we are declaring wish method as synchronized we will get regular o/p
because at a time only one thread is allowed to execute wish method.

Display d1 = new Display();


Display d2 = new Display();
MyThread t1 = new MyThread(d1,"Dhoni");
MyThread t2 = new MyThread(d2,"Yuvraj");
t1.start();
t2.start();
Even though wish method is synchronized we will get irregular o/p only because both threads are
operating on different objects.

Class level lock: If a thread want to execute any static synchronized method then compulsory that
thread should require class level lock.
While a thread executing any static synchronised method then the remaining threads are not allowed
to execute any static synchronized method of the same class simultaneously.
But the remaining threads are allowed to execute any non-synchronized static methods,
synchronized – instance method, non – synchronized instance method simultaneously.

Declare static synchronized in display method and try the above example we will get regular o/p
because there is class level lock.

Synchronized Blocks
It is not recommended to declare entire method as synchronized if very few lines of code requires the
synchronization concept. Such a few lines of code we can declare in a block rather than declaring
entire method as a synchronized method

Syntax:
synchronized(b)
{
//critical section.
}
Where ‘b’ is an object reference.
To get the lock for the current object we can define synchronized block as follows
synchronized(this)
{
//critical section.
}
We can define synchronized block to get class level as follows
synchronized(Display.class)
we can define synchronized block either for object references or for class references But not for
primitives violation leads to Compile time error.
int i =10;
synchronized(i)
{
//------
}
C.E:- unexpected type
found : int.
required : reference.

Synchronized statement(Only for Interview Purpose):


The statement which are defined in inside synchronized method or synchronized blocks are called
‘synchronized statement’.

Inter Thread Communication


Two threads can communicate with each other by using wait(), notify(), notifyAll().
These methods are available in object class but not in thread class. Because threads are calling these
methods on any object.
We should call these methods only from synchronized area other wise we get runtime exception
saying
IllegalMonitorStateException.
If a thread executes wait() method it immediately releases the lock of that object(But not all locks)
and entered into waiting state.
After giving the notification also the thread releases the lock but may not be immediately.
public final void wait() throws InterruptedException
public final void wait(long ms) throws InterruptedException
public final void wait(long ms, int ns) throws InterruptedException
public final void notify();
public final void notifyAll();

sleep(): It is a static method on Thread class. It makes the current thread into the "Not Runnable"
state for specified amount of time. During this time, the thread keeps the lock (monitors) it has
acquired.
wait(): It is a method on Object class. It makes the current thread into the "Not Runnable" state. Wait
is called on a object, not a thread. Before calling wait() method, the object should be synchronized,
means the object should be inside synchronized block. The call to wait() releases the acquired lock.

Ex:
class ThreadA
{
public static void main(String arg[])throws InterruptedException
{
ThreadB b = new ThreadB();
b.start();
synchronized(b)
{
System.out.println("Main thread is trying to call wait()");
b.wait();
System.out.println("Main thread got notification");
System.out.println(b.total);
}
}
}
class ThreadB extends Thread
{
int total = 0;
public void run()
{
synchronized(this)
{
System.out.println("Child thread starts calculation");
for(int i = 1; i<=100; i++)
{
total = total + i;
}
System.out.println("child thread trying to give notification ");
this.notify();
}
}
}
Dead Lock
If two threads are waiting for each other forever, then the threads are said to be in “deadlock”.
There is no deadlock resolution technique but prevention technique are available
Ex:
Banker’s Algorithm.
Ex:
class A
{
synchronized void foo(B b)
{
System.out.println("Thread 1 entered foo() method");

try
{
Thread.sleep(600);
}
catch (InterruptedException e)
{
}
System.out.println("Thread 1 is trying to call b.last()");
b.last();
}
synchronized void last()
{
System.out.println("Inside A, This is last() method");
}
}
class B
{
synchronized void bar(A a)
{
System.out.println("Threas 2 entered bar() method");
try
{
Thread.sleep(600);
}
catch (InterruptedException e)
{
}
System.out.println("Thread 2 is trying to call a.last()");
a.last();
}
synchronized void last()
{
System.out.println("Inside B, This is last() method");
}
}
class DeadLock implements Runnable
{
A a = new A();
B b = new B();
DeadLock()
{
Thread t = new Thread(this);
t.start();
b.bar(a);
}
public void run()
{
a.foo(b);
}
public static void main(String arg[])
{
new DeadLock();
}
}

DaemonThread
The threads which are running in the background to provide support for user defined threads are
called
“Daemon Thread”. Usually daemon thread are running with low priority but based on our
requirement we
can increase their priority also.
We can check whether the given thread is daemon or not by using the following thread class thread.
public boolean isDaemon()
we can change the daemon nature of a thread by using setDaemon() method of thread class.
public void setDaemon(Boolean b)
the daemon nature of a thread is inheriting from the parent. i.e if the parent is daemon then the child
is also
daemon and if the parent is non – daemon then the child is also non – daemon.
After starting a thread we are not allowed to change the daemon nature violation leads to runtime
exception
saying IllegalThreadStateException.

Ex:
class MyThread extends Thread
{
}
class Test
{
public static void main(String arg[])
{
System.out.println(Thread.currentThread().isDaemon());
MyThread t = new MyThread();
System.out.println(t.isDaemon());
t.setDaemon(true);
System.out.println(t.isDaemon());
t.start();
//t.setDaemon(false); -1
}
}

If we don’t comment line 1 we will get the IlleagalThreadStateException, see the following o/p.
We can’t change the daemon nature of main thread because it has started already before main()
method only.
All the daemon threads will be terminated automatically when ever last non – daemon thread
terminates.

Ex:
1

If we are commenting line 1, then both child and main threads are non – Daemon, hence they will
execute until their completion.
If we are not commenting line 1, then the child thread is daemon and hence it will terminate
automatically
when ever main() thread terminates.

You might also like