我正在查看公司中一个旧的Java项目,发现作者(已经离开了公司)创建和运行线程时没有继承Thread类或实现Runnable接口。值得注意的是,该类是单例模式。代码片段如下:
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();
}
}
这种方法如何运作——使用线程而不需要扩展Thread类或实现Runnable接口? 使用这种方法的优缺点是什么(不扩展和实现有哪些优缺点)?
Thread
的匿名子类。 - Sotirios Delimanolis