Java并行任务,仅执行一次
我的代码不是并行执行任务, 在这种情况下,它只执行一次代码(for循环中的任何内容,但应为2):Java并行任务,仅执行一次,java,multithreading,parallel-processing,Java,Multithreading,Parallel Processing,我的代码不是并行执行任务, 在这种情况下,它只执行一次代码(for循环中的任何内容,但应为2): 公共类mqDirect{ 公共静态void main(字符串args[])引发异常{ int并行度=2; 执行器服务执行器服务= Executors.newFixedThreadPool(并行); 信号量信号量=新信号量(并行性); 对于(int i=0;i
公共类mqDirect{
公共静态void main(字符串args[])引发异常{
int并行度=2;
执行器服务执行器服务=
Executors.newFixedThreadPool(并行);
信号量信号量=新信号量(并行性);
对于(int i=0;i<1;i++){
试一试{
semaphore.acquire();
//剪断…做些事情。。
semaphore.release();
}捕捉(可抛可抛){
semaphore.release();
}
executorService.shutdownNow();
}
}
}
在Java中,使代码并行工作的主要方法是创建一个新的构造函数参数。那你就需要去做了
有许多教程可以帮助您正确实现这一点
在代码运行时,您只需创建一个执行器服务
(而不是使用它),创建一个信号灯
(这应该在线程中完成,但不是),执行一些过程,然后关闭执行器
顺便说一句:shutdownow
可能不是您想要的,您应该使用ShutDown
我拥有的这段代码不是并行执行任务,它在这种情况下只执行一次代码(for循环中的任何代码,但应该是2):
仅仅因为实例化了一个ExecutorService
实例,并不意味着事情神奇地并行运行。除了关闭它之外,您实际上还需要使用该对象
如果希望循环中的内容在服务的线程中运行,则需要执行以下操作:
int parallelism = 2;
ExecutorService executorService = Executors.newFixedThreadPool(parallelism);
for (int i = 0; i < parallelism; i++) {
executorService.submit(() -> {
// the code you want to be run by the threads in the exector-service
// ...
});
}
// once you have submitted all of the jobs, you can shut it down
executorService.shutdown();
// you might want to call executorService.awaitTermination(...) here
int并行度=2;
ExecutorService ExecutorService=Executors.newFixedThreadPool(并行);
for(int i=0;i{
//要由exector服务中的线程运行的代码
// ...
});
}
//提交所有作业后,可以将其关闭
executorService.shutdown();
//您可能需要在此处调用executorService.WaitiveTermination(…)
请务必注意,这将在服务中运行您的代码,但不能保证它将“并行”运行。这取决于处理器的数量和线程固有的竞争条件。例如,第一个任务可能会在第二个任务启动之前启动、运行并完成其代码。这就是线程程序的本质,线程程序的设计是异步的
但是,如果您至少有2个内核,并且提交给executor服务运行的代码需要很长时间才能运行,那么它们很可能在某个时间点同时运行
最后,正如@OldCurmudgeon指出的,您应该在服务上调用shutdown()
,它允许已提交给服务的当前作业运行,而不是shutdownNow()
,它取消并排队作业,并在任何正在运行的作业上调用thread.interrupt()
希望这有帮助。好的,所以我找到了这本很好的教程
我做过类似的事情
public class mqDirect {
int poolSize = 2;
int maxPoolSize = 2;
long keepAliveTime = 10;
ThreadPoolExecutor threadPool = null;
final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
5);
public mqDirect()
{
threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize,
keepAliveTime, TimeUnit.SECONDS, queue);
}
public void runTask(Runnable task)
{
threadPool.execute(task);
System.out.println("Task count.." + queue.size());
}
public void shutDown()
{
threadPool.shutdown();
}
public static void main (String args[]) throws Exception
{
mqDirect mtpe = new mqDirect();
// start first one
mtpe.runTask(new Runnable()
{
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
System.out.println("First Task");
runMqTests();
Thread.sleep(1000);
} catch (InterruptedException ie)
{
}
}
}
});
// start second one
/*
* try{ Thread.sleep(500); }catch(InterruptedException
* ie){}
*/
mtpe.runTask(new Runnable()
{
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
System.out.println("Second Task");
runMqTests();
Thread.sleep(1000);
} catch (InterruptedException ie)
{
}
}
}
});
mtpe.shutDown();
// runMqTests();
}
公共类mqDirect{
int poolSize=2;
int maxPoolSize=2;
长keepAliveTime=10;
ThreadPoolExecutor threadPool=null;
最终ArrayBlockingQueue队列=新ArrayBlockingQueue(
5);
公共mqDirect()
{
threadPool=新的ThreadPoolExecutor(池大小、maxPoolSize、,
keepAliveTime,TimeUnit.SECONDS,queue);
}
公共无效运行任务(可运行任务)
{
执行(任务);
System.out.println(“任务计数..”+queue.size());
}
公共空间关闭()
{
threadPool.shutdown();
}
公共静态void main(字符串args[])引发异常
{
mqDirect mtpe=新的mqDirect();
//从第一个开始
mtpe.runTask(新的Runnable()
{
公开募捐
{
对于(int i=0;i<2;i++)
{
尝试
{
System.out.println(“第一个任务”);
runMqTests();
睡眠(1000);
}捕获(中断异常ie)
{
}
}
}
});
//开始第二个
/*
*尝试{Thread.sleep(500);}catch(InterruptedException
*ie){}
*/
mtpe.runTask(新的Runnable()
{
公开募捐
{
对于(int i=0;i<2;i++)
{
尝试
{
System.out.println(“第二个任务”);
runMqTests();
睡眠(1000);
}捕获(中断异常ie)
{
}
}
}
});
mtpe.shutDown();
//runMqTests();
}
而且它有效!
但问题是,这个重复的代码…runMqtests()是同一个任务,有没有办法指定它在不重复代码的情况下并行运行
基于此,我的示例假设每个任务都不同。抱歉,尽管我尝试格式化代码,但不允许我发布代码。。您可以将代码发布为文本,其他人可能可以将其编辑为形状。您的示例创建了一个它从未使用过的ExectorService
实例。为什么“…创建线程
…然后需要启动它或使用执行器
。"依我看,这很混乱。你似乎建议通过创建一个新的线程
实例来解决问题,然后使用执行器
对新的线程
做些什么。这毫无意义。你可能是想建议使用执行器
而不是使用线程
,但我不认为你是这么做的你的答案应该是一个不熟悉线程池概念的新手。
public class mqDirect {
int poolSize = 2;
int maxPoolSize = 2;
long keepAliveTime = 10;
ThreadPoolExecutor threadPool = null;
final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
5);
public mqDirect()
{
threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize,
keepAliveTime, TimeUnit.SECONDS, queue);
}
public void runTask(Runnable task)
{
threadPool.execute(task);
System.out.println("Task count.." + queue.size());
}
public void shutDown()
{
threadPool.shutdown();
}
public static void main (String args[]) throws Exception
{
mqDirect mtpe = new mqDirect();
// start first one
mtpe.runTask(new Runnable()
{
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
System.out.println("First Task");
runMqTests();
Thread.sleep(1000);
} catch (InterruptedException ie)
{
}
}
}
});
// start second one
/*
* try{ Thread.sleep(500); }catch(InterruptedException
* ie){}
*/
mtpe.runTask(new Runnable()
{
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
System.out.println("Second Task");
runMqTests();
Thread.sleep(1000);
} catch (InterruptedException ie)
{
}
}
}
});
mtpe.shutDown();
// runMqTests();
}