Professional Documents
Culture Documents
Java Thread Explained in Detail
Java Thread Explained in Detail
Java Thread Explained in Detail
6. Terminated- At any time, a thread can be terminated, which halts its execution
immediately. Once terminated, a thread cannot be resumed.
The main thread
When a Java program starts up, one thread begins running immediately.
This is called as Main / Demon thread. The main thread is important for two
reasons
1. It is the thread from which other child threads will be spawned.
2. Often it must be last thread to finish execution because it performs
various shutdown actions.
The main thread is created automatically, but it can be controlled through a Thread
object by using a method
static Thread currentThread() Returns a reference to the thread in which it is
called.
Example- of main Thread
class cthread
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println("Current Thread-"+t);
// Change the name of threadt.setName("New Thread");
System.out.println("After name changed-"+t);
try
{
for(int n=5;n>0;n--)
{
System.out.println ("n-"+n);
Thread.sleep (1000);
}
}
catch(InterruptedException ie)
{ System.out.println("Main thread interrupted"); }
}
}
The details of thread displayed areName of the thread
Priority, by default it is 5.
Name of the group of threads to which this thread belongs to. Thread group
is a data structure that controls the state of a collection of threads as a whole.
The methods to handle threads are-
class newthread1
{
public static void main(String args[])
{
new threaddemo();
try
{
for(int n=5;n>0;n--)
{
System.out.println("Main thread-"+n);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{ System.out.println("Main thread interrupted");
System.out.println("Exiting main thread");
}
}
opChild Thread-Thread[Demo thread,5,main]
Main thread-5
Child thread-5
Child thread-4
Main thread-4
Child thread-3
Child thread-2
Main thread-3
Child thread-1
Exiting child thread
Main thread-2
Main thread-1
Exiting main thread
opNew Thread-Thread[one,5,main]
New Thread-Thread[two,5,main]
New Thread-Thread[three,5,main]
one:5
two:5
three:5
one:4
two:4
three:4
one:3
two:3
three:3
one:2
two:2
three:2
one:1
two:1
three:1
one Exiting
two Exiting
three Exiting
Exiting main thread
finally
{
try
{ netClient.close ();
catch (Exception e)
}
}
}
}
{
class multithreaddemo
{
public static void main(String args[])
{
nthread ob1=new nthread("one");
nthread ob2=new nthread("two");
nthread ob3=new nthread("three");
System.out.println("Thread one is alive:"+ob1.t.isAlive());
System.out.println("Thread two is alive:"+ob2.t.isAlive());
System.out.println("Thread three is alive:"+ob3.t.isAlive());
//waits for threads to finish
try
{
System.out.println("Waiting for threads to finish");
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{ System.out.println("Main thread interrupted"); }
System.out.println("Thread one is alive:"+ob1.t.isAlive());
System.out.println("Thread two is alive:"+ob2.t.isAlive());
System.out.println("Thread three is alive:"+ob3.t.isAlive());
System.out.println("Exiting main thread");
}
}
Thread Priorities- Java assigns to each thread a priority that determines how that thread should be
treated with respect to others.
- Thread priorities are integers that specify the relative priority of one thread to
another.
Thread priority is used to decide when to switch from one running thread to the
next. This is called Context switch.
In theory, higher priority threads get more CPU time than lower-priority threads.
In practice, the amount of CPU time that a thread gets often depends on several
factors besides its priorities. A higher priority thread can preempt the lower priority
thread.
Method1. To set the threads priorityFinal void setPriority (int level)
level specifies the new priority setting for the calling thread. The value of
level must be within a range MIN_PRIORITY & MAX_PRIORITY. i.e. from 1
to 10. By default it is 5 i.e. NORM_PRIORITY
2. To obtain the current priorityfinal int getPriority()
Synchronization
- When 2 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 monitor (also called a semaphore). A
monitor is an object that is used to mutually exclusive lock. Only one thread can
own a monitor at a given time. When a thread acquires a lock, it is said to have
entered the monitor. All other threads attempting to enter the locked monitor will be
suspended until first thread exits monitor.
Using Synchronized methodsIn Java, all objects have their own implicit monitor. To enter an objects monitor, just
call a method that has been modified with the synchronized keyword.
If the class is already defined with some methods, & to use synchronize, use calls
to methods defined by this class inside a synchronized block.
The form issynchronized(object) { //statements to synchronized }
Exampleclass callme
{
void call(String msg)
{
System.out.println(msg);
try
{ Thread.sleep(100000);}
catch(InterruptedException e)
{ }
}
}
class caller implements Runnable
{
String msg; callme target; Thread t;
public caller (callme targ, String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run()
{
synchronized(target)
{ target.call(msg); }
}
}
class synch1
{
public static void main(String args[])
{
callme target=new callme();
caller ob1=new caller(target,"hello");
caller ob2=new caller(target,"Synchronised");
caller ob3=new caller(target,"world");
try
{
ob1.t.join(); ob2.t.join(); ob3.t.join();
}
catch(InterruptedException e) { }
}
}
Life cycle of a thread- Thread just created is in born state, waits for start() method to be called & even
then it is in a ready to run state. This thread enters the running state when system
allocates processor to thread.
- Execution can be halted temporarily with sleep() method. thread becomes ready
after sleep time expires. Within this time the thread doesnt use processor.
- Thread enters in waiting state when a running thread calls wait() method. again
enters to ready state when notify() method is given by other thread associated with
that object.
- Thread enters as blocked state when performing input-output operations. Again
enters ready state when input-output it is waiting for is completed.
- Enters a dead state after complete execution of run() or its stop() method is
called.
sleep ()
suspend ()
New Thread
wait ()
start ()
Runnable
Dead
Blocked
resume ()
notify ()
stop ()
Assignments Ans.
1. Program to create a Traffic Signal.
import java.awt.*; import java.applet.*;
/*<applet code=signal width=200 height=200> </applet>*/
public class signal extends Applet implements Runnable
{
Thread t=null;
int cnt;
public void init()
{cnt=1; }
public void paint(Graphics g)
{
if (cnt==1)
{
g.setColor(Color.red);
g.fillOval(5,5,40,40);
g.setColor(Color.black);
g.drawOval(5,55,40,40);
g.drawOval(5,105,40,40);
}
else if(cnt==2)
{
g.setColor(Color.black);
g.drawOval(5,5,40,40);
g.setColor(Color.yellow);
g.fillOval(5,55,40,40);
g.setColor(Color.black);
g.drawOval(5,105,40,40);
}
else if(cnt==3)
{
g.setColor(Color.black);
g.drawOval(5,5,40,40);
g.drawOval(5,55,40,40);
g.setColor(Color.green);
g.fillOval(5,105,40,40);
}
}
public void start()
{ t=new Thread(this, "signal");
t.start(); }
}
}
//inner thread
class BouncingBallThread extends Thread {
Point top, bottom, current;
Color color;
int radius;
boolean down = true;
public BouncingBallThread (int xCoor, int height, int radius, Color color)
{
this.current = new Point(xCoor, 0);
this.top = new Point(xCoor, 0);
this.bottom = new Point(xCoor, height);
this.radius = radius;
this.color = color;
}
public void run () {
Graphics g = getGraphics();
while(!done) {
g.setColor(Color.white);
g.fillOval(current.x, current.y, radius,radius);
if (down) {
int t = current.y+5;
if (t > bottom.y)
down = false;
else
current.y = t;
}
else {
int t = current.y - 5;
if (t < top.y)
{ down = true;}
else
current.y = t;
}
g.setColor(color);
g.fillOval(current.x, current.y, radius,radius);
try { Thread.sleep(50); }
catch(InterruptedException e) {}
}}}}