Posted August 15th, 2008 by Ramakrishna
Interrupted Exception is the most important exception which frequently occurs in the thread programming
EX:
java.lang
Class InterruptedException
java.lang.Object
|___extended byjava.lang.Throwable
|___extended byjava.lang.Exception
|___extended byjava.lang.InterruptedException
All Implemented Interfaces:
Serializable
public class InterruptedException
extends Exception
Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.
Since:
JDK1.0
See Also:
Object.wait(), Object.wait(long), Object.wait(long, int), Thread.sleep(long), Thread.interrupt(), Thread.interrupted(), Serialized Form
–>InterruptedException
public InterruptedException()
Constructs an InterruptedException with no detail message.
–>InterruptedException
public InterruptedException(String s)
Constructs an InterruptedException with the specified detail message.
Parameters:
s – the detail message.
Posted August 15th, 2008 by Ramakrishna
The extending class must override the method run() mehtod. Which is the entry point of the new thread.It must also call the start() to begin execution of the new thread.
Here is the proceding program rewritten to extend thread
Ex#1:
//create a second thread by extending Thread
class NewThread extends Thread{
NewThread() {
//create a new,second thread
super(“Demo Thread);
System.out.println(“child thread:”+this);
start(); //start the thread
}
//This is the entry point for the second thread.
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 ExtendThread{
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”);
}
}
Posted August 15th, 2008 by Ramakrishna
Def. of Thread: A Thread represents a process (or)
execution of a statment one by one by the Microprocessor(JVM) is called Thread.
Note: Every java program will have a thread.
The basic usage of the thread is as follows:
In the most general sense, you can create a thread by instantiating an object of type thread.
There are two ways to create a new thread.
–> You can Extend the Thread class in your class and override the method run().
Syntax :
public class MyThread extends Thread
{
public void run()
{
——
}
}
–> You can implement the Runnable interface and use that class in the Thread constructor
Syntax :
public class MyThread implements Runnale
{
public void run()
{
——
}
}