Java调用Groovy 简单例子

 
  

------------------------------ 简单demo  ---------------------------------------

-- 

package b.groovy;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
import groovy.lang.GroovyObject;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestGroovy002 {

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();


        ScriptEngineManager manager = new ScriptEngineManager();

        ScriptEngine engine = manager.getEngineByName("groovy");
        Bindings bindings =     engine.createBindings();

        for (int i = 0; i < 100000; i++) {
            Map map = new HashMap<>();
//            map.put("name","tom"+i);
            bindings.put("map",map);
            Object eval2 = engine.eval(" map.remove('a');  map['name']='55'; return map;", bindings);
            System.out.println(eval2);
        }
        System.out.println(System.currentTimeMillis()-start);

    }
}


------------------------------ 多线程 运行groovy ---------------------------------------


package c.groovy;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Map;

public class GroovyUtils {

    ScriptEngineManager manager = new ScriptEngineManager();

    public ScriptEngine getScriptEngine(){
        ScriptEngine engine = manager.getEngineByName("groovy");
        return  engine;
    }


    public void execute(ScriptEngine engine,String tname) throws ScriptException {
        Bindings bindings = engine.createBindings();
        Map map = new HashMap<>();
        map.put("name",tname);
        bindings.put("map", map);
        Object e = engine.eval(" map.remove('a');  map['name']='"+tname+"'; return map;", bindings);
        System.out.println(e);

        assert ("{name="+tname+"}").equals(e.toString());
    }

}
package c.groovy;

import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class ThreadTestGroovy {


    public static void testXC(){

        GroovyUtils g = new GroovyUtils();
        ScriptEngine scriptEngine1 = g.getScriptEngine();

        for (int i = 0; i < 1000; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                         g.execute(scriptEngine1,Thread.currentThread().getName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, "T"+i).start();
        }

    }

    public static void main(String[] args) {
        testXC();
    }

}


你可能感兴趣的:(groovy)