java - 每个 tomcat 创建一个实例

标签 java multithreading tomcat java-threads

我有一个名为 Test 的类,它在 10 秒的延迟内打印从 1 到 100 的数字。如果我从命令提示符打开它并尝试运行它将开始打印数据。如果我打开第二个命令提示符并运行该程序,它将起作用。但我想限制它只能从单个命令提示符运行。我们该怎么做。

这是我的代码

public class ThreadDelay{
    public static void main(String[] args) throws InterruptedException {
        Test t1= new Test();
        t1.start();


    }

}
class Test extends Thread{
    public void run(){
        for(int i=0;i<100;i++){
            System.out.println("Value of i ===:"+i);
            Thread t=new Thread();
            try {
                t.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        }
}

最佳答案

使用单例模式。最简单的实现包括一个私有(private)构造函数和一个用于保存其结果的字段,以及一个名称类似于 getInstance() 的静态访问器方法。

私有(private)字段可以从静态初始化程序 block 中分配,或者更简单地说,使用初始化程序。 getInstance() 方法(必须是公共(public)的)然后简单地返回这个实例,

public class Singleton {
    private static Singleton instance;

    /**
     * A private Constructor prevents any other class from
     * instantiating.
     */
    private Singleton() {
        // nothing to do this time
    }

    /**
     * The Static initializer constructs the instance at class
     * loading time; this is to simulate a more involved
     * construction process (it it were really simple, you'd just
     * use an initializer)
     */
    static {
        instance = new Singleton();
    }

    /** Static 'instance' method */
    public static Singleton getInstance() {
        return instance;
    }

    // other methods protected by singleton-ness would be here...
    /** A simple demo method */
    public String demoMethod() {
        return "demo";
    }
}

关于java - 每个 tomcat 创建一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43750786/

相关文章:

java - 如果 Excel 文件打开,则 Java 程序无法访问 Excel 文件

java - Java,数组,线程数,最小值,最大值

c# - Monitor.Pulse 丢失信号?

eclipse - 使用 Eclipse 远程调试 Tomcat

apache - HTTP KeepAlive 连接被服务器关闭但客户端同时发送了一个请求

java - 绞刑吏游戏 : stuck on randomly selecting players

java - Java 8 是否支持多重继承?

java - 为什么来自 'Concurrency in practice' 的 CooperatingNoDeadlock 使用与同一监视器的双同步?

python - 我如何进行异步编程但将其隐藏在 Python 中?

maven - 是否可以调整 atlassian-sdk 以不在控制台消息中显示 [INFO] [talledLocalContainer] 前缀?