I was going through an old project (Java) in my company where I found the author (already left), creates and runs thread without extending the Thread class or implementing the Runnable interface. One noticable thing was that the class was a singleton class. There are no usage of thread pooling, or the new concurrent package from java. Code snippet outlines given below –
import java.sql.*; import org.apache.log4j.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; public class DataLookup { private static DataLookup _ref; private DataLookup() { } public static DataLookup getInstance() { if (_ref == null) { synchronized (DataLookup.class) { if (_ref == null) { _ref = new DataLookup(); } } return _ref; } } /* * Implementation Logic */ public void writeRecord(String a, String b, String c) { /* * Implementation Logic */ Thread writerThread = new Thread() { public void run() { /* * Implementation Logic */ } } writerThread.start(); } }
How does this approach work – using threads without extending from Thread class or implementing Runnable interface? What are the advantages and disadvantages of using this approach (without extends and implements).
Advertisement
Answer
Thread writerThread = new Thread() { public void run() { /* * Implementation Logic */ } }
This code creates an anonymous class that extends Thread
.
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
The above quote is taken from The Java Tutorials, where you can read more about them.