Java 为每个tomcat创建一个实例
我有一个名为Test的类,它以10秒的延迟将数字从1打印到100。如果我从命令提示符下打开它并尝试运行它,它将开始打印数据。如果我打开第二个命令提示符并运行此程序,它将工作。但我想限制它只能从单个命令提示符运行。我们怎么能做到呢 这是我的密码Java 为每个tomcat创建一个实例,java,multithreading,tomcat,java-threads,Java,Multithreading,Tomcat,Java Threads,我有一个名为Test的类,它以10秒的延迟将数字从1打印到100。如果我从命令提示符下打开它并尝试运行它,它将开始打印数据。如果我打开第二个命令提示符并运行此程序,它将工作。但我想限制它只能从单个命令提示符运行。我们怎么能做到呢 这是我的密码 public class ThreadDelay{ public static void main(String[] args) throws InterruptedException { Test t1= new Test();
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();
}
}
}
}
公共类线程延迟{
公共静态void main(字符串[]args)引发InterruptedException{
测试t1=新测试();
t1.start();
}
}
类测试扩展了线程{
公开募捐{
对于(int i=0;i使用单例模式。最简单的实现包括一个私有构造函数和一个保存其结果的字段,以及一个名为getInstance()
的静态访问器方法
私有字段可以从静态初始值设定项块中分配,或者更简单地说,使用初始值设定项分配。然后getInstance()
方法(必须是公共的)只返回此实例
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";
}
}
您基本上只希望创建线程的单个实例。
如果您将线程声明为实例变量和静态,那么它将适用于您
public class ThreadDelay {
static Thread t;
...
只需在运行块中写入t=new Thread();
更新:您可能希望在Tomcat应用服务器上运行您的类。
您还需要使用单例类
来处理多个线程类
对象的创建。(如果一次打开数十个命令提示窗口).您的标题和文本冲突。是Tomcat还是命令行?就像每个设备上只能运行该程序的一个实例一样?我会用一种蹩脚的方法打开一个本地Socket
,如果有一个已经打开,则您知道该程序正在其他地方运行。