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 ? My code is as follows: I saved this file as 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:
G:\\ZPREP>javac TwoClass.java
G:\\ZPREP>java TwoClass I am first class
G:\\ZPREP>java TwoClass2 I am Second class
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
; 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:
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:
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.