我在我的代码中调用两个不同的主类,但是我想同时运行它们。
for (int m=0; m<ListUser.size();m++){
System.out.println(ListUser.get(m));
File user = new File(ManagedPlatformPath.properties()+"/"+ListPlatform.get(n)+" /"+ListUser.get(m)+".adf");
if(user.exists()){
System.out.println("Reading Information "+ListUser.get(m)+"");
BACControlS.main(args);
BACControlT.main(args);
}
else{
System.out.println("Not Information "+ListUser.get(m)+"");
}
如何同时运行BACControlS.main(args)和BACControlT.main(args),而不是等到一个完成。
答案 0 :(得分:1)
产生两个线程。
new Thread(new Runnable() {
public void run() {
BACControlS.main(args);
}
}).start();
new Thread(new Runnable() {
public void run() {
BACControlT.main(args);
}
}).start();
为了将args传递给那些Runnable
,您可能需要将args
声明为final
答案 1 :(得分:1)
你应该使用线程。您可以将其运行为:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
BACControlS.main(args);
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
BACControlT.main(args);
}
});
t2.start();
而不是
BACControlS.main(args);
BACControlT.main(args);
答案 2 :(得分:0)
没有办法可以运行2个类,因为两个主类都假设是不同的进程。所以你能做的就是使用线程。线程可以并行运行。如果两个踏板都在一个过程中,则CPU将其作为单个过程将其视为单个过程。
答案 3 :(得分:0)
使用java.util.concurrent.ExecutorService。正如其他anwsers建议的那样,在循环中创建java.lang.Thread是一个坏主意,因为线程不是无限的资源,但是你的用户名列表可能很大。
以下是java.util.concurrent.ExecutorService代码的外观:
ExecutorService executorService = Executors.newFixedThreadPool(10);
try
{
for (String userName : users)
{
File userFile = ...
if (userFile.exists())
{
System.out.println("Reading Information " + userName);
executorService.execute(
new Runnable()
{
public void run()
{
BACControlS.main(args);
}
}
);
executorService.execute(
new Runnable()
{
public void run()
{
BACControlT.main(args);
}
}
);
}
else
{
System.out.println("Not Information " + userName);
}
}
}
finally
{
executorService.shutdown();
}