THREADS
THREADS
What is Thread
• A multithreaded program contains two or more parts that can run concurrently.
Each part of that program is called thread.
• The thread is a dispatchable code. This means that a single program can
perform two or more program task simultaneously
Uses of threads
p1 p2
p3 p4
Web Application
Gaming
How to create thread
Extending thread
Implements runnable
Extending Thread
NewThread() { try {
for(int i = 5; i > 0; i--) {
// Create a new, second thread
System.out.println("Child Thread: " + i);
t = new Thread(this, "Demo
Thread.sleep(500);
Thread");
}
System.out.println("Child
} catch (InterruptedException e) {
thread: " + t);
System.out.println("Child interrupted.");
t.start(); // Start the thread
}
}
System.out.println("Exiting child thread.");
}}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread
interrupted.");
}
System.out.println("Main thread exiting.");
}}
Important methods
Method Meaning
getName Obtain a thread’s name.
getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
start Start a thread by calling its run method.
Thank you