2017-05-03 71 views
0

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

这是我的代码

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(); 
      } 
     } 
     } 
} 
+0

您的标题和文本冲突。这是什么,Tomcat或命令行? –

+0

因此,只有该程序的一个实例可以在每个设备上运行?我只是做一个蹩脚的方式,并打开一个本地'套接字',如果有一个已经打开,那么你知道该程序正在其他地方运行。 – 3kings

回答

0

使用Singleton模式。最简单的实现包含一个私有构造函数和一个保存其结果的字段,以及一个名为getInstance()的静态访问方法。

私有字段可以从静态初始化块内分配,或者更简单地说,使用初始化程序。要创建的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"; 
    } 
} 
0

你基本上只想要threadsingle instance
如果你将线程声明为一个实例变量并且是静态的,那么它就可以为你工作。

public class ThreadDelay { 
    static Thread t; 
    ... 

只写t=new Thread();内部运行块。


更新:您可能想要在Tomcat应用程序服务器上运行您的类。
您还需要使用Singleton class来处理创建多个Thread class对象。 (在一次打开几十个命令提示符窗口的情况下)。

相关问题