Java Thread Explained in Detail

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 24

Java Multithreading

Java provides built in support for multithreaded programming. Multithreaded


program contains two or more parts that can run concurrently. Each part of such a
program is called a Thread, and each thread defines a separate path of execution.
Multithreading enables you to write efficient programs that make maximum
use of the CPU. Thus multithreading is a specialized form of multitasking.
There are two distinct types of multitasking:
a. Process based- A process is a program that is executing.
- It is the feature that allows your computer to run two or more
programs concurrently.
- Ex.- Running Java compiler, when you are using TextEditor.
b. Thread based- Thread is the smallest unit of dispatchable code.
- That is, a single program can perform two or more programs
simultaneously.
- Ex.- Text editor can format text at the same time that it is printing.
Multitasking Processes
Multitasking Threads
1. Processes are heavyweight tasks
1. Threads are lightweight tasks that
that require their own separate address share the same address space &
spaces.
cooperatively share the same
heavyweight processes.
2. Interprocess communication is
2. Interthread communication is
expensive & limited.
inexpensive.
3. Context switching from one process 3. Context switching from one thread to
to other is also costly.
other is low cost.
Java Thread Model
Java run-time system depends on threads for many things, and all the class
libraries are designed with multithreading in mind.
The benefit of Javas multithreading is that main loop mechanism is
eliminated.
One thread can pause without stopping other parts of your program.
Multithreading allows loops to slip for a second between each frame
without causing the whole system to pauses.
States of Thread1. Blocked- A thread can be blocked when waiting for a resource.
2. Run- Thread is ready to run as soon as it gets CPU time.
3. Running- Thread using CPU.
4. Suspended- A running thread can suspended, which temporarily suspended its
activity.
5. Resumed- A suspended thread can then be resumed, allowing to pick up where
it left off.

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-

1. static void sleep(long millisec) throws InterruptedException


- to specify number of mllisec, to which thread should be suspended.
2. final void setName(String threadname)- to set the thread name.
3. final String getName()
- to obtain name of thread.
Creating a ThreadYou can create a thread by instantiating an object of type Thread.
Java defines two ways in which this can be accomplished1. You can implement the Runnable interface.
2. By extending a Thread class.
Implementing Runnable interfaceTo implement a Runnable, a class need to implement a single method called
run(). The form is- public void run()
Inside this method define a code that constitutes new thread. run() method can call
other methods, can declare variables, just like main thread can. The only
difference is that run() establishes entry point for another, concurrent thread of
execution within your program.
Constructor for creating a Threadpublic Thread (String threadname)
Thread (Runnable threadobj, String threadName)
After creation of threads, it will not start running until you call its start()
method. start() executes a call to run() method.
The form is- void start()

Exampleclass threaddemo implements Runnable


{
Thread t;
threaddemo ()
{
// create a new thread
t=new Thread (this, "Demo Thread1");
System.out.println ("Child Thread-"+t);
t.start ();
}
// this is entry point for new thread.
public void run()
{
try
{
for(int n=5;n>0;n--)
{
System.out.println("Child thread-"+n);
Thread.sleep (500);
}
}
catch(InterruptedException ie)
{ System.out.println("Child thread interrupted"); }
System.out.println("Exiting child thread");
}
}
class newthread
{
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 Thread1,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
Extending a Thread
- The second way to create a thread is to create a new class that extends Thread,
and then to create instance of that class.
- The extending class must override run() method.
- It must also call start() to begin execution of the new thread.
Exampleclass threaddemo extends Thread
{
threaddemo()
{
// create a new thread
super("Demo thread");
System.out.println("Child Thread-"+this);
start();
}
// this is entry point for new thread.
public void run()
{
try
{
for(int n=5;n>0;n--)
{
System.out.println("Child thread-"+n);
Thread.sleep(500);
}
}
catch(InterruptedException ie)
{ System.out.println("Child thread interrupted");
System.out.println("Exiting child thread");
}
}

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

Creating Multiple Threads


class nthread implements Runnable
{
String name;
Thread th;
nthread(String threadname)
{
// create a new thread
name=threadname;
th=new Thread (this, name);
System.out.println("New Thread-"+th);
th.start();
}
public void run()
{
try
{
for(int n=5;n>0;n--)
{
System.out.println(name+":"+n);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{ System.out.println(name+" thread interrupted"); }
System.out.println(name+" Exiting");
}
}
class multithreaddemo
{
public static void main(String args[])
{
new nthread ("one");
new nthread ("two");
new nthread ("three");
try
{ Thread.sleep (10000);
}
catch(InterruptedException ie)
{ System.out.println ("Main thread interrupted"); }
System.out.println("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

Example1. Creating a Time Clock.


import java.util.*; import java.awt.*; import java.applet.*;
/*<applet code=tclock width=200 height=200> </applet>*/
public class tclock extends Applet implements Runnable
{
Thread t=null;
Date d;
String s;
TextField tf;
public void start()
{
t=new Thread(this, "clock");
t.start();
}
public void run()
{
for( ; ;)
{
try
{
d=new Date();
s=d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
repaint();
Thread.sleep(1000);
}
catch(InterruptedException e)
{ System.out.println (e); }
}
}
public void paint(Graphics g)
{
g.drawString(s,10,50);
}
}

2. Creating a Simple Banner Appletimport java.awt.*; import java.applet.*;


/*<applet code="simplebanner" width=300 height=300> </applet>*/
public class simplebanner extends Applet implements Runnable
{
String msg="A simple moving banner. ";
Thread t=null;
public void init()
{ setBackground(Color.cyan); setForeground(Color.red); }
public void start()
{
t=new Thread(this);
t.start();
}
public void run()
{
char ch;
for(; ;)
{
try
{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
}
catch(InterruptedException e) { }
}
}
public void paint(Graphics g)
{ g.drawString(msg,50,50);}
}

3. Creating a multi-client chatting application


//client Side
import java.net.*; import java.io.*;
public class client1
{
public static void main(String a[])
{
int cn;
try {
Socket cls;
DataInputStream in=null;
DataOutputStream ous=null;
try {
cls=new Socket("localhost",1001);
InputStream i=cls.getInputStream();
in=new DataInputStream(i);
OutputStream o=cls.getOutputStream();
ous=new DataOutputStream(o);
}
catch(Exception e)
{
System.out.println(" Could not I/O ");
System.exit(0);
}
BufferedReader stdin=new BufferedReader (new InputStreamReader (System.in));
while(true)
{
System.out.println("Enter message");
String s1=stdin.readLine();
if (s1.equals("EXIT"))
{ ous.writeUTF(s1); break; }
ous.writeUTF(s1);
System.out.println("Message send to server, waiting for reply..");
String s2=in.readUTF();
System.out.println("server says-"+s2);
}
ous.close(); in.close(); stdin.close();
} catch(Exception e1) { }
}
}

//Multithreaded server application


import java.io.*; import java.net.*;
public class server1 extends Thread
{
ServerSocket ss;
int i=0; Socket cl;
public server1()
{
try
{
ss=new ServerSocket (1001);
System.out.println (ss.toString ());
}
catch(Exception e)
{ System.out.println (" Server Fail "); }
System.out.println (" Server Started.....");
this.start();
}
public void run()
{
try
{
while(true)
{
cl=ss.accept();
System.out.println((i+1)+" Client(s) connected");
Conn con=new Conn(cl); i++;
}
}
catch (IOException e)
{
System.out.println (" Error ");
}
}
public static void main(String ar[])
{ new server1(); }
}
class Conn extends Thread
{
Socket netClient;
DataInputStream fromc=null;
DataOutputStream toc=null;

public Conn(Socket cl)


{
netClient=cl;
try
{
InputStream i=netClient.getInputStream();
fromc=new DataInputStream(i);
OutputStream o=netClient.getOutputStream();
toc=new DataOutputStream(o);
}
catch(IOException e)
{
try
{ netClient.close();
}
catch(IOException e1)
{
System.out.println(" Unable to set Stream" +e1);
return;
}
}
this.start();
}
public void run()
{
String s1,s2;
DataInputStream di=new DataInputStream(System.in);
try{
while(true)
{
s1=fromc.readUTF ();
System.out.println ("from client"+netClient.getPort());
if(s1.equals("EXIT"))
{
System.out.println ("Client says EXIT");
break;
}
System.out.println ("Client says-"+s1);

System.out.println ("Enter message");


s2=di.readLine ();
toc.writeUTF (s2);
System.out.println ("Message send to client");
s2="";s1="";
}
}
catch (Exception i)

finally
{
try
{ netClient.close ();
catch (Exception e)
}
}
}

}
{

Using isAlive () & join ()


Two ways to determine whether a thread is finished or nota. final boolean isAlive ()- This method is defined by Thread class.
- Returns True if the thread upon which it is called is still running,
otherwise returns false.
b. final void join () throws InterruptedException
- Commonly used to wait for a thread to finish.
- This method waits until the thread on which it is called terminates.
- It comes from the concept of calling thread waiting until the specified
thread joins it.
Exampleclass nthread implements Runnable
{
String name;
Thread t;
nthread(String threadname)
{
// create a new thread
name=threadname;
t=new Thread (this, name);
System.out.println("New Thread-"+t);
t.start();
}
public void run()
{
try
{
for(int n=5;n>0;n--)
{
System.out.println(name+":"+n);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{ System.out.println(name+" thread interrupted"); }
System.out.println(name+" Exiting");
}
}

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) { }
}
}

Interthread CommunicationIn Java Interprocess communication is possible by wait(), notify(), notifyAll()


methods. These methods are implemented as final methods in Object, so all
classes have them.
All three methods can be called only from within a synchronized method.
The rules of using these methods are1. wait() tells the calling thread to give up the monitor & go to sleep
until some other thread enters the same monitor & calls notify().
final void wait() throws InterruptedException
2. notify()- wakes up the first thread that called wait() on same object.
final void notify()
3. notifyAll()- wakes up all threads that called wait() on the same object.
The highest priority thread will run first.
final void notifyAll()
class Q
{
int n;
boolean valueset=false;
synchronized int get()
{
if(!valueset)
try { wait();}
catch(InterruptedException e) { }
System.out.println("got-"+n);
valueset=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueset)
try { wait();}
catch(InterruptedException e) { }
this.n=n;
valueset=true;
System.out.println("Put-"+n);
notify();
}
}

class producer implements Runnable


{
Q q;
producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
q.put(i++);
}
}
class consumer implements Runnable
{
Q q;
consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class democ
{
public static void main(String args[])
{
Q q=new Q();
new producer(q);
new consumer(q);
}
}
[ The Formsto suspend & resume threadsex.- ob1.t.suspend ()
ob1.t.resume ()

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 ()

Daemon threadThreads that are intended to be background threads providing service to


other threads are referred as daemon threads. JVM has at least one daemon
thread, known as garbage collection thread. It is a low priority thread & executes
only when there are no tasks for system to do.

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(); }

public void run()


{
for( ; ;)
{
try
{
if(cnt==3)
cnt=1;
else
cnt++;
repaint();
Thread.sleep(1000);
}
catch(InterruptedException e)
{ System.out.println(e); }
}
}
}
2. Bouncing Ball Applet
// VerticalBall1.java: Define threads using the Thread class
import java.awt.*; import java.awt.event.*; import java.applet.*;
/*<applet code=Verticalball1 width=100 height=100> </applet>*/
public class Verticalball1 extends Applet {
//switch for stopping thread
boolean done = false;
BouncingBallThread thread;
public void init() {
int radius = 20;
Color color = Color.RED;
System.out.println(getHeight());
thread = new BouncingBallThread(getWidth()/2 - radius/2, getHeight()- radius
, radius, color);
}
public void start() { thread.start();
public void stop() { done = true;

}
}

//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) {}
}}}}

You might also like