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

What do you mean by Socket Programming?

546


Why do I get a duplicate name error when loading a jar file?

542


Why does the tag url-encode javascript and mailto links?

578


Where we can write Rmi registry in the code, without having to write it at the command prompt?

2258


What is a class loader? What are the different class loaders used by jvm?

583






Difference between DurableSubscription and non- DurableSubscription?

1714


To identify IDL language what mapping mechanism is used?

3415


Java is fully object oriented languages or not?

538


Why is string immutable in java?

577


How is a java object message delivered to a non-java client?

571


Can you control when passivation occurs?

598


Why does the option tag render selected=selected instead of just selected?

673


how to make a index.jsp for running the site in internet and find an error for connection with weblogic server and java that give an error invalid object name.and how to maintain session.

1750


How are commas used in the intialization and iteration parts of a for statement?

581


What is re-entrant. Is session beans reentrant. Is entity beans reentrant?

578