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

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

Which containers use a border layout as their default layout?

699


Is a class a subclass of itself?

677


What are the difference between RMI and CORBA?

702


What is colon_pkg_prefixes and what is its use?

2082


What is local interface. How values will be passed?

654






Name three subclasses of the component class?

707


Explain phantom read?

1828


how to use debug in my elipse to solve problems that exist in my project

1853


Can I have an action without a form?

686


What is the difference between long.class and long.type?

660


What is the argument type of a programs main() method?

651


What is a modular application?

679


What are JTA/JTS and how they used by client?

1820


A user of a web application sees a jsessionid argument in the URL whenever a resource is accessed. What does this mean? a. The form must have the field jsessionid b. URL rewriting is used as the session method c. Cookies are used for managing sessions

1908


Have you used threads in Servelet?

2048