[讨论][探索]优雅的并发执行代码.

来源:互联网 发布:永宏官网plc编程软件 编辑:程序博客网 时间:2024/05/17 23:19

先看这段代码,java:

        int a = 1;//step 1        int b = 一段执行10秒的方法();//step 2        int c = 一段执行15秒的方法();//step 3        int d = b + c;//step 4

在这里,第二步和第三步是不需要先后执行的,我希望它们可以同时执行,只要执行第4步之前第2,3步执行完就可以了.

那么,有什么好的解决办法呢?


再看go语言:

    resultChan:=make(chan int,2)    go 耗时方法(values[:len(values)/2],resultChan)    go 耗时方法(values[len(values)/2:],resultChan)    sum1,sum2:=<-resultChan,<-resultChan

这个解决方案挺好的!

再回到java语言中,修改后的代码:

    static int b;//step 2.1    static int c;//step 3.1    private static int aMethod() throws InterruptedException {        int a = 1;//step 1        Thread t1 = new Thread(() -> b = 一段执行10秒的方法());//step 2.2        t1.start();//step 2.3                Thread t2 = new Thread(() -> c = 一段执行15秒的方法());//step 3.2        t2.start();//step 3.3        t1.join();//step 2.4        t2.join();//step 3.4        int d = b + c;//step 4        return d;//step 5    }

虽然代码长的太丑了,但是好在功能实现了,LOL.

groovy语言的代码:

int 一段执行10秒的方法() { loop(10); 2 }int 一段执行15秒的方法() { loop(15); 3 }def loop(int times) {    times.times {        Thread.sleep(1000)        println "loop $it"    }}def threads = []def results = []threads << Thread.start { results << 一段执行10秒的方法() }threads << Thread.start { results << 一段执行15秒的方法() }threads*.join()println results.sum()


最后,实际运行时go语言开销最好,因为go语言就是协程,而java,groovy用的线程.

0 0