By : Prof.
Kumar Anand Singh
Kumar Anand Singh
What is a Thread?
• Individual and separate unit of execution that is part of a
process
– multiple threads can work together to accomplish a common goal
• Video Game example
– one thread for graphics
– one thread for user interaction
– one thread for networking
Kumar Anand Singh
What is a Thread?
Video Game
Process
video networking
interaction
Kumar Anand Singh
Advantages
• easier to program
• 1 thread per task
• can provide better performance
• thread only runs when needed
• no polling to decide what to do
• multiple threads can share resources
• utilize multiple processors if available
Kumar Anand Singh
Disadvantage
• multiple threads can lead to deadlock
• much more on this later
• overhead of switching between threads
Kumar Anand Singh
How to create threads
• There are two ways of creating threads in Java:
1) Extend the “Thread” class
We can instantiate the class Thread as many times as desired to achieve multi-
threading.
2) Implement the “Runnable” interface
Since multiple inheritance is not allowed in Java, this method is used when the
program already extends another class (Ex. Applets)
Kumar Anand Singh
1) Extend the Thread class
• Create a subclass of java.lang.Thread:
public class MyThread extends Thread {
public void run() {
\\put code here
}
}
• Instantiate MyThread:
MyThread myTrd;
myTrd.start(); // calls run() in MyThread
Kumar Anand Singh
Methods in Class Thread
• Three primary methods to control a thread:
• public native synchronized void start() prepares a thread to run
• public void run() actually performs the work of the thread
• public final void stop() to terminate the thread. The thread also dies when run()
terminates.
• Other important methods in Thread include:
• suspend() and resume()
• sleep(mls) which causes the thread to temporarily stop execution for mls milliseconds
• yield() which causes the executing thread object to temporarily pause and allow other
threads to execute
• getName() and getPriority()
Kumar Anand Singh
Class Thread Priorities
• The class Thread has three fields:
• MAX_PRIORITY
• MIN_PRIORITY
• NORM_PRIORITY: the default priority assigned to a thread
• A new created thread has its priority initially set equal to the priority of
the creating thread.
Kumar Anand Singh
Ex1
class MyThread extends Thread { // the thread
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx1 { // a program that utilizes the thread
public static void main(String [] args ) {
MyThread t = new MyThread();
// due to extending the Thread class (above) we can call start()
// start() will invoke run(). start() is a predefined method in class Thread.
t.start();
}
}
Kumar Anand Singh
Ex: 2 public class C extends Thread {
public class A extends Thread { String []name={"Anand", “Ravi", “Neha", “Nikita", “Devanshi",
public void run(){ “Marlin", “Siddharth"};
for(int i=0;i<7;i++){ public void run(){
System.out.println("Thread A "+i); for(int i=0;i<7;i++){
} System.out.println("Thread B "+name[i]);
System.out.println("Thread A exit"); }
} System.out.println("Thread B exit");
}
} }
public class Multi_Thread {
public class B extends Thread { public static void main(String[] args)throws
public void run(){ RuntimeException{
for(char c='a';c<'g';c++){ A a=new A(); B b=new B(); C c=new C();
System.out.println("Thread C "+c); a.start();
} b.start();
System.out.println("Thread C exit"); c.start();
} }
} }
Kumar Anand Singh
2) Creating a thread by using Runnable Interface
• Instantiate Thread and pass it “this” (the applet) as a parameter.
• Use the method start() to start running the instantiated thread.
• Place all the important code for the instantiated thread in the run()
method.
• Set the instantiated thread to “null” in the stop() method.
Kumar Anand Singh
Implement Runnable interface
• Create a class that implements Runnable:
public class MyThread extends Applet implements Runnable;
• Runnable is an interface in java.lang that contains only one method: run().
• Multiple inheritance is not allowed in Java, thus this method of creating
threads is used when MyThread already extends another class.
Kumar Anand Singh
Threads by implementing Runnable interface
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
• Creating Object:
MyThread myObject = new MyThread();
• Creating Thread Object:
Thread thr1 = new Thread( myObject );
• Start Execution:
thr1.start();
Kumar Anand Singh
Ex 1
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
// due to implementing the Runnable interface
// It can call start(), and this will call run().
t.start();
} // end main()
} // end class Thread
Kumar Anand Singh
Ex 2
public class B implements Runnable{
public class A implements Runnable{ String []name={"Anand", "Abhijit", "Lalita",
public void run(){ "Apurva","Meghna","Vishal","Alpesh"};
for(int i=0;i<7;i++){ public void run(){
System.out.println("Thread A "+i); for(int i=0;i<7;i++){
} System.out.println("Thread B "+name[i]);
System.out.println("Thread A exit"); }
} System.out.println("Thread B exit");
} }
}
public class Main_Thread {
public static void main(String[] args) {
A a=new A();
B b=new B();
Thread threadA=new Thread(a);
Thread threadB = new Thread(b);
threadA.start();
threadB.start();
}
}
Kumar Anand Singh
Advantage of Using Runnable
• remember – we can only extend one class at a time
• implementing runnable allows class to extend something else like an
applet
Kumar Anand Singh
Life cycle of a Thread Newborn
• Newborn state start() stop()
• Runnable state Dead
Runnable state
• Running state
• Blocked state
• Dead state
Kumar Anand Singh
Kumar Anand Singh
Methods used in Thread and there meanings
• yield() : if we want a thread to relinquish (hand over) to another
thread to equal priority before its turn comes.
• suspend() : if we want to turn a thread in waiting state
• resume() : if a thread is in waiting state then it can be revived
• sleep() : We can put a thread to wait state for a specified time in milli
seconds
• wait() : this method wait to resume thread for some event to ocour
• notify() : if a thread is in wait condition then using notify we can again
resume the thread
Kumar Anand Singh
The End
21