简体   繁体   English

每个线程一个“Java上下文”?

[英]One “Java context” per thread?

Is it possible to launch a Java program from another Java program, just as if I were launching it using another Java command? 是否可以从另一个Java程序启动Java程序,就像我使用另一个Java命令启动它一样? When calling the main() method of a program from another program directly, the Java context is common to these both executions. 当直接从另一个程序调用程序的main()方法时, Java上下文对于这两个执行都是通用的。 I'm trying to have one Java context per thread. 我正在尝试每个线程有一个Java上下文

Illustration: 插图:

src/com/project/ProjectLauncher.java SRC / COM /项目/ ProjectLauncher.java

public class ProjectLauncher {

    static {
        PropertyConfigurator.configure("log4j.properties");
    }

    public static void main(String[] args) {
        Logger.getLogger(ProjectLauncher.class).info("started!");
        // Logs well as expected.
    }

}

test/com/project/TestProject.java 测试/ COM /项目/ TestProject.java

public class TestProject extends TestCase {

    public void testProject() {
        ProjectLauncher.main(null);
        Logger.getLogger(TestProject.class).info("tested!");
        // The above line logs well, while log4j has been initialized in ProjectLauncher.
        // I would like it to need its own initialization in this class.
    }

}

I tried to launch the main method in another thread/runnable, but the logger is still initialized by ProjectLauncher. 我尝试在另一个线程/ runnable中启动main方法,但是LogLaher仍然初始化了记录器。

Well when you start a Java process, its a new Instance of JVM. 好吧,当你启动Java进程时,它是一个新的JVM实例。 If you wish to start another JVM instance, then you need to start a separate process of it. 如果您希望启动另一个JVM实例,那么您需要启动它的单独进程。

ie

    List<String> command = new ArrayList<String>();
    command.add("java");
    command.add("ProjectLauncher");
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.redirectErrorStream(true);
    final Process process = builder.start();
        try {
           process.waitFor();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        //if you wish to read the output of it then below code else you can omit it.
        InputStream is = process.getErrorStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            Logger.getLogger(MyClass.class.getName()).severe(line);
        }

Above we are ultimately starting a new process which in reality is java ProjectLauncher . 上面我们最终开始了一个新的过程,实际上是java ProjectLauncher In case if the class is not already compiled, then you will have to compile it similar to above but using javac instead of java and ProjectLauncher.java instead of ProjectLauncher etc. 如果该类尚未编译,那么您将必须编译它类似于上面但使用javac而不是javaProjectLauncher.java而不是ProjectLauncher等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM