Creating streams without extensions and implementation

I went through an old project in my company (Java), where I found the author (already on the left), creates and starts a thread without extending the Thread class or implementing the Runnable interface. One of the notable things was that the class was a single class. There is no use of thread pool or new concurrent package from java. Following are the diagrams of code snippets -

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 the Thread class or implementing the Runnable interface? What are the advantages and disadvantages of using this approach (no extensions and tools).

+3


source to share


1 answer


Thread writerThread = new Thread()
{
  public void run() 
  {
    /*
     * Implementation Logic
    */
  }
}

      

This code creates an anonymous class that extends Thread

.



Anonymous classes make your code more concise. They allow you to declare and instantiate a class at the same time. They are similar to local classes, except that they have no name. Use them if you only need to use the local class once.

The above quote is from the Java Tutorials where you can read more about them.

+7


source







All Articles