What are the ways to define classes that can be run as
threads?



What are the ways to define classes that can be run as threads?..

Answer / ranganathkini

1. Have the class extend the java.lang.Thread class and
override the run() method. Example:

public class MyThread extends Thread {
// override the run method
public void run() {
// .. the thread code
}

public static void main( String[] args ) {
MyThread mt = new MyThread();
mt.start();
}
}

2. Have the class implement the java.lang.Runnable interface
and implement the run() method. Then create a new instance
of java.lang.Thread and pass the class instance reference as
a parameter to the constructor of the Thread class. Example:

public class MyThread implements Runnable {
public void run() {
// .. thread code here
}

public static void main( String[] args ) {
Thread theThread = new Thread( new MyThread() );
theThread.start();
}
}

3. Create an inner class (static or non-static) using
eiether technique 1 or 2. Example:

public class MyTestProgram {
private class MyThread implements Runnable {
public void run() {
// .. the thread code
}
}

public static void main( String[] args ) {
Thread theThread = new Runnable( this.new MyThread() );
theThread.start();
}
}

4. Create an anonymouse class of eiether java.lang.Runnable
or java.lang.Thread, override the run() method. Example:

public class TestProgram {
public static void main( String[] args ) {
Thread theThread = new Thread( new Runnable() {
public void run() {
// .. thread code here
}
} );
theThread.start();
}
}

Is This Answer Correct ?    5 Yes 0 No

Post New Answer

More Advanced Java Interview Questions

difference between Abstract and Interface?

2 Answers   HCL, Infotech,


What is ripple effect?

0 Answers  


How many requests can a server fetch at a time?

1 Answers  


What is ioc concept & explain it?

0 Answers  


What is servlet preinitialization?

3 Answers   iFlex,






Urgent Openings for Java and .NET ( India, Singapore, Australia, Japan)

2 Answers   Wipro,


What are synchronized methods and synchronized statements?

2 Answers   Adobe,


diff between jsp include directive and jsp action include?

4 Answers   SolutionNET,


Can a thread be a member of another thread?

2 Answers  


what is a portable component?

0 Answers  


Is 'synchronised' a modifier?

2 Answers   NIIT,


What is chat area? Explain.

0 Answers  


Categories