如何在Java代码中使用多线程/并发
这是我的代码的简化:如何在Java代码中使用多线程/并发,java,multithreading,Java,Multithreading,这是我的代码的简化: for(int i = 0; i < 500; i++) { someMethod(i); } 因此,我可以为不同的I同时执行someMethod() 如何使用多线程来实现这一点 请帮忙!谢谢 在这种情况下,建议使用greatExecutorService代码。您要做的是将所有任务(0到499)提交到线程池中,它们将由池中的5个线程并发运行 如下所示: // create a thread pool with 5 workers ExecutorServic
for(int i = 0; i < 500; i++) {
someMethod(i);
}
因此,我可以为不同的I
同时执行someMethod()
如何使用多线程来实现这一点
请帮忙!谢谢 在这种情况下,建议使用great
ExecutorService
代码。您要做的是将所有任务(0到499)提交到线程池中,它们将由池中的5个线程并发运行
如下所示:
// create a thread pool with 5 workers
ExecutorService threadPool = Executors.newFixedThreadPool(5);
// submit all of your jobs here
for (int i = 0; i < 500; i++) {
threadPool.submit(new MyJob(i));
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
// if you need to wait for the pool you can do
threadPool.awaitTerminatation(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
建议在这种情况下使用great
ExecutorService
代码。您要做的是将所有任务(0到499)提交到线程池中,它们将由池中的5个线程并发运行
如下所示:
// create a thread pool with 5 workers
ExecutorService threadPool = Executors.newFixedThreadPool(5);
// submit all of your jobs here
for (int i = 0; i < 500; i++) {
threadPool.submit(new MyJob(i));
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
// if you need to wait for the pool you can do
threadPool.awaitTerminatation(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
使用ExecutorServices和threadpoolSmall and really basic sample使用ExecutorServices和threadpoolSmall and really basic sample By
//这里的线程是什么意思?另外,someMethod()
在这其中起到了什么作用?因此@Jessica,您可以复制someMethod()
中的内容,并将代码放入run()
。您还可以传入将线程分叉到MyJob
构造函数中的类,然后传入rundo:caller.someMethod(i)
。你的选择。只要用someMethod(i)替换//这里的线程工作
代码>:)+还有一个问题,如果还有人在场:我的代码开头有一个boolean done=false
。其中一个i
值将切换done
。当这种情况发生时,我想停止for循环。现在我添加了if(done)return
到run()
但是所有已经启动的someMethod()
都需要返回代码>所以有很短的时间延迟。有什么更好的方法可以做到这一点?因为作业已经提交到线程池,所以更难。你可以让done
变得易变,只要在(done)返回时输入
run()
method@Jessica.By//这里的线程是什么意思?另外,someMethod()
在这其中起到了什么作用?因此@Jessica,您可以复制someMethod()
中的内容,并将代码放入run()
。您还可以传入将线程分叉到MyJob
构造函数中的类,然后传入rundo:caller.someMethod(i)
。你的选择。只要用someMethod(i)替换//这里的线程工作
代码>:)+还有一个问题,如果还有人在场:我的代码开头有一个boolean done=false
。其中一个i
值将切换done
。当这种情况发生时,我想停止for循环。现在我添加了if(done)return
到run()
但是所有已经启动的someMethod()
都需要返回代码>所以有很短的时间延迟。有什么更好的方法可以做到这一点?因为作业已经提交到线程池,所以更难。你可以让done
变得易变,只要在(done)返回时输入
run()方法@Jessica中的第一件事是code>。
private static class MyJob implements Runnable {
private int i;
public MyJob(int i) {
this.i = i;
}
public void run() {
// do the thread stuff here
}
}