[英]How to run two classes at a time in CMD in Java
Hello I create one java file which contains two classes TwoClass and TwoClass2 On compilation it gives me two class files separately but I have to run each class file separately.. How can I do this ?您好,我创建了一个包含两个类TwoClass和TwoClass2 的java 文件 在编译时,它分别给了我两个类文件,但我必须分别运行每个类文件..我该怎么做? My code is as follows: I saved this file as TwoClass.java我的代码如下:我将此文件保存为TwoClass.java
class TwoClass{
public static void main(String args[])
{
System.out.println("I am first class");
}}class TwoClass2{
public static void main(String args[])
{
System.out.println("I am Second class");
}}
After compilation it generates TwoClass.class and TwoClass2.class Now if I want to run this files I do as follows:编译后它生成TwoClass.class和TwoClass2.class现在如果我想运行这个文件我做如下:
G:\\ZPREP>javac TwoClass.java G:\\ZPREP>javac TwoClass.java
G:\\ZPREP>java TwoClass I am first class G:\\ZPREP>java TwoClass 我是头等舱
G:\\ZPREP>java TwoClass2 I am Second class G:\\ZPREP>java TwoClass2 我是二等舱
G:\\ZPREP> G:\\ZPREP>
There is no problem here at all but I have to run each file separately so any thing is their to run both files at a time ???这里完全没有问题,但我必须单独运行每个文件,所以他们一次运行两个文件是什么???? Please help.请帮忙。
Rather than trying to do it in the command line, use a third class to run two threads, one per class, so both your classes' main method will run at the same time, using the same args
;与其尝试在命令行中执行此操作,不如使用第三个类来运行两个线程,每个类一个,这样您的两个类的 main 方法将使用相同的args
同时运行; something like this:像这样:
class TwoclassMain {
public static void main(final String ... args) {
Runnable runnableOne = new Runnable {
public void run() { TwoClass.main(args); }
}
Runnable runnableTwo = new Runnable {
public void run() { TwoClass2.main(args); }
}
Thread one = new Thread(runnableOne);
Thread two = new Thread(runnableTwo);
one.start();
two.start();
one.join();
two.join();
}
}
DISCLAIMER: I haven't compiled and run this example, is just to show the general idea.免责声明:我没有编译和运行这个例子,只是为了展示一般的想法。
UPDATE: Same idea using Java 8:更新:使用 Java 8 的相同想法:
class TwoclassMain {
public static void main(final String ... args) {
Thread one = new Thread(() -> TwoClass.main(args));
Thread two = new Thread(() -> TwoClass2.main(args));
one.start();
two.start();
one.join();
two.join();
}
}
On the command line you can chain commands with &&
.在命令行上,您可以使用&&
链接命令。 After each command completes successfully the next will run.每个命令成功完成后,下一个将运行。 Eg,例如,
javac TwoClass.java && java TwoClass && java TwoClass2
Or you could have one main
method call the other:或者您可以让一个main
方法调用另一个:
class TwoClass {
public static void main(String args[]) {
System.out.println("I am first class");
TwoClass2.main(args);
}
}
Or write a third to call them both:或者写第三个来称呼他们两个:
class Foo {
public static void main(String args[]) {
TwoClass.main(args);
TwoClass2.main(args);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.