多线程

    xiaoxiao2021-11-02  66

    public class Main { private static MyRunnable runnable1 = new MyRunnable(file1,url1); private static MyRunnable runnable2 = new MyRunnable(file2,url2); private static MyRunnable runnable3 = new MyRunnable(file3,url3); private static MyRunnable runnable4 = new MyRunnable(file4,url4); public static void main(String[] args) { final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4); for (int i = 0; i < 2000; i++) { fixedThreadPool.execute(runnable1); fixedThreadPool.execute(runnable2); fixedThreadPool.execute(runnable3); fixedThreadPool.execute(runnable4); } fixedThreadPool.shutdown(); } }

    这是自己瞎写的,主要是为了能4个线程同时执行。。凑活了。。

    主要要加上TestNG,实现如下:

    @Test(invocationCount = 1000) public void test() throws ExecutionException, InterruptedException { final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10); Future future1 = fixedThreadPool.submit(runnable1); Future future2 = fixedThreadPool.submit(runnable2); Future future3 = fixedThreadPool.submit(runnable3); Future future4 = fixedThreadPool.submit(runnable4); Future future5 = fixedThreadPool.submit(runnable5); Future future6 = fixedThreadPool.submit(runnable6); Future future7 = fixedThreadPool.submit(runnable7); Future future8 = fixedThreadPool.submit(runnable8); Future future9 = fixedThreadPool.submit(runnable9); Future future10 = fixedThreadPool.submit(runnable10); future1.get(); future2.get(); future3.get(); future4.get(); future5.get(); future6.get(); future7.get(); future8.get(); future9.get(); future10.get(); fixedThreadPool.shutdown(); }

    以下是根据String值来找到类,执行方法

    public class Main { public void method(String fileName, String url) { if (!fileName.equals("")) { DataInit.init(fileName); } try { Class<?> cla = Class.forName("com.jane.classname." + className); Method method = cla.getMethod("getNo", String.class); method.invoke(cla.newInstance(), url); } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.getCause().printStackTrace();//防止报异常(java.lang.reflect.InvocationTargetException),特殊处理 } } }
    转载请注明原文地址: https://ju.6miu.com/read-677936.html

    最新回复(0)