IT 2402notes-39
IT 2402notes-39
Lecture Notes – 39
Creating Threads
Creating Threads:
To create a new thread a program will either:
1) extends the Thread class, or
2) implement the Runnable interface
Thread class encapsulates a thread of execution. The whole Java multithreading
environment is based on the Thread class.
Thread Methods:
• Start: a thread by calling start its run method
• Sleep: suspend a thread for a period of time
• Run: entry-point for a thread
• Join: wait for a thread to terminate
• isAlive: determine if a thread is still running
• getPriority: obtain a thread’s priority
• getName: obtain a thread’s name
M. Satish (IT)
Object Oriented Programming through JAVA Unit – 3
// Thread constructor – the new thread will call this
// object’s run method:
NewThread()
{
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
//This is the entry point for the newly created thread – a five-iterations loop
//with a half-second pause between the iterations all within try/catch:
public void run()
{
try
{
for (int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo
{
public static void main(String args[])
{
//A new thread is created as an object of
// NewThread:
new NewThread();
//After calling the NewThread start method,
M. Satish (IT)
Object Oriented Programming through JAVA Unit – 3
// control returns here.
//Both threads (new and main) continue concurrently.
//Here is the loop for the main 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.");
}
}
M. Satish (IT)