gpt4 book ai didi

java - 创建没有扩展和实现的线程

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:44 24 4
gpt4 key购买 nike

我正在研究我公司的一个旧项目(Java),在那里我找到了作者(已经离开),创建并运行线程而不扩展 Thread 类或实现 Runnable 接口(interface)。一件值得注意的事情是该类是单例类。没有使用线程池,也没有使用 java 的新并发包。代码片段概述如下 -

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 接口(interface)?使用这种方法的优点和缺点是什么(没有扩展和实现)。

最佳答案

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

这段代码创建了一个扩展 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 Java Tutorials ,您可以在其中阅读有关它们的更多信息。

关于java - 创建没有扩展和实现的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26088200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com