gpt4 book ai didi

java - 在 Java 中并行执行代码

转载 作者:行者123 更新时间:2023-12-02 06:13:09 25 4
gpt4 key购买 nike

我有一个非常基本的脚本,它执行 Redis 服务器请求,但我对多线程了解不够,无法成功使其并行运行。这就是我的 main() 方法

        Jedis jedis1 = new Jedis("10.10.25.54", 6381);
Jedis jedis2 = new Jedis("10.10.25.54", 6382);
Jedis jedis3 = new Jedis("10.10.25.54", 6383);
Jedis jedis4 = new Jedis("10.10.25.54", 6384);
Jedis jedis5 = new Jedis("10.10.25.54", 6385);
Jedis jedis6 = new Jedis("10.10.25.54", 6386);
Jedis jedis7 = new Jedis("10.10.25.54", 6387);
Jedis jedis8 = new Jedis("10.10.25.54", 6388);

// The bit i would like to learn how run in parallel
//
System.out.println(jedis1.eval(SCRIPT, 0).toString());
System.out.println(jedis2.eval(SCRIPT, 0).toString());
System.out.println(jedis3.eval(SCRIPT, 0).toString());
System.out.println(jedis4.eval(SCRIPT, 0).toString());
System.out.println(jedis5.eval(SCRIPT, 0).toString());
System.out.println(jedis6.eval(SCRIPT, 0).toString());
System.out.println(jedis7.eval(SCRIPT, 0).toString());
System.out.println(jedis8.eval(SCRIPT, 0).toString());

最佳答案

多线程和并发是 Java 中一个相当大的主题,太大而无法用一个问题来回答,并且有许多可能的解决方案。不过我建议阅读 Orical Concurrency tutorials

我的方法是:

ExecutorService es = Executors.newCachedThreadPool();

es.submit(new RunJedis(jedis1));
es.submit(new RunJedis(jedis2));
es.submit(new RunJedis(jedis3));
es.submit(new RunJedis(jedis4));
es.submit(new RunJedis(jedis5));
es.submit(new RunJedis(jedis6));
es.submit(new RunJedis(jedis7));
es.submit(new RunJedis(jedis8));

class RunJedis{
Jedis jedis;
RunJedis(Jedis jedis1){
this.jedis=jedis1;
}

void run(){
System.out.println(jedis.eval(SCRIPT, 0).toString());
}
}

但是,这不能保证使用多个线程。您将其留给执行者服务来决定如何最好。

关于java - 在 Java 中并行执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21709473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com