Search code examples
javapythonconcurrencyparallel-processingjython

Execute multiple functions at same time in Jython 2.5


I'm trying to run multiple Jython files at the same time so that I can use my PC multiprocessor (specifically doing this in FDM in Hyperion's Workspace)

Is there any way I could do this?

I've tried to do it through Java, but it doesn't recognize the thread function, also tried through Python, and this version of Jython doesn't have the concurrency library, and not able to import it.

import os
import sys
from java.io import *
from java.util import *
from java import *
from java.lang import *
from threading import *
import java.util.logging.Level;
import java.util.logging.Logger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;


new Thread() { 
    public void run() {
        java.lang.Runtime.getRuntime().exec("python test1.py")
    }
}.start()
new Thread() { 
    public void run() {
        java.lang.Runtime.getRuntime().exec("python test2.py")
    }
}.start()
new Thread() { 
    public void run() {
        java.lang.Runtime.getRuntime().exec("python test3.py")
    }
}.start()

Errors:

File "E:\Oracle\Middleware\EPMSystem11R1\products\FinancialDataQuality\Applications\FDMEE/data/scripts/custom/test.py", line 15
    new Thread() {
       ^
SyntaxError: mismatched input 'Thread' expecting NEWLINE

Solution

  • You cannot use Java syntax in python code. Even if you're running it with Jython.

    You can use the fact that Jython will convert python functions to Java functional interface.

    from java.lang import Thread, Runtime
    
    
    Thread(lambda: Runtime.getRuntime().exec("python test1.py")).start()
    Thread(lambda: Runtime.getRuntime().exec("python test2.py")).start()
    Thread(lambda: Runtime.getRuntime().exec("python test3.py")).start()
    

    Pythonic way to do the same would be

    import subprocess, threading
    
    threading.Thread(target=lambda: subprocess.call(["python","test1.py"])).start()
    threading.Thread(target=lambda: subprocess.call(["python","test2.py"])).start()
    

    To be honest I would use multiprocessing instead of threading, but I am not sure if Jython supports it.