如何在Java中并发执行相同的方法
抱歉,如果这是一个非常基本/愚蠢的问题 我有一个方法,需要几分钟才能运行。我想在多个对象上同时运行此方法。我在想我该怎么做?甚至只是指向正确文档的指针。我不确定我是否应该使用线程,或者ExecuteService或者什么 下面是我想同时运行的方法。我想同时删除多个vm如何在Java中并发执行相同的方法,java,multithreading,concurrency,Java,Multithreading,Concurrency,抱歉,如果这是一个非常基本/愚蠢的问题 我有一个方法,需要几分钟才能运行。我想在多个对象上同时运行此方法。我在想我该怎么做?甚至只是指向正确文档的指针。我不确定我是否应该使用线程,或者ExecuteService或者什么 下面是我想同时运行的方法。我想同时删除多个vm private void deleteVm(String workspace, String vmName) { println("Delete VirtualMachine: " + vmName + " in Work
private void deleteVm(String workspace, String vmName) {
println("Delete VirtualMachine: " + vmName + " in Workspace " + workspace);
Job job = executeDelete(getWorkbench().deleteVirtualMachine(sub(), workspace, vmName));
println(job);
subscribeToJobLogs(job);
awaitUntilJobNotRunningOrNotFound(() -> executeCall(getWorkbench().getVirtualMachineDeleteJob(sub(), workspace, vmName)));
}
最简单的方法是使用
最简单的方法是使用
若要同时调用方法,则需要线程。并发性的Java文档: 您可以选择如何在java中创建/使用线程 (一) 如果您知道需要多少线程,您可以像下面这样手动创建线程:
Thread thread1 = new Thread(()->deleteVm("a","b");
Thread thread2 = new Thread(()->deleteVm("c","d");
//START the threads
thread1.start();
thread2.start();
CompletableFuture.runAsync(() -> deleteVm("a", "b"));
CompletableFuture.runAsync(() -> deleteVm("c", "d"));
(二)
您可以像这样使用默认线程池(通常是每个cpu核心的线程):
Thread thread1 = new Thread(()->deleteVm("a","b");
Thread thread2 = new Thread(()->deleteVm("c","d");
//START the threads
thread1.start();
thread2.start();
CompletableFuture.runAsync(() -> deleteVm("a", "b"));
CompletableFuture.runAsync(() -> deleteVm("c", "d"));
(三)
您可以像这样创建自己的线程执行器
ScheduledExecutorService executorService = Executors.nScheduledExecutorService executorService = Executors.newFixedThreadPool(5)
executorService.submit(() -> deleteVm("a", "b"));
executorService.submit(() -> deleteVm("c", "d"));
若要同时调用方法,则需要线程。并发性的Java文档: 您可以选择如何在java中创建/使用线程 (一) 如果您知道需要多少线程,您可以像下面这样手动创建线程:
Thread thread1 = new Thread(()->deleteVm("a","b");
Thread thread2 = new Thread(()->deleteVm("c","d");
//START the threads
thread1.start();
thread2.start();
CompletableFuture.runAsync(() -> deleteVm("a", "b"));
CompletableFuture.runAsync(() -> deleteVm("c", "d"));
(二)
您可以像这样使用默认线程池(通常是每个cpu核心的线程):
Thread thread1 = new Thread(()->deleteVm("a","b");
Thread thread2 = new Thread(()->deleteVm("c","d");
//START the threads
thread1.start();
thread2.start();
CompletableFuture.runAsync(() -> deleteVm("a", "b"));
CompletableFuture.runAsync(() -> deleteVm("c", "d"));
(三)
您可以像这样创建自己的线程执行器
ScheduledExecutorService executorService = Executors.nScheduledExecutorService executorService = Executors.newFixedThreadPool(5)
executorService.submit(() -> deleteVm("a", "b"));
executorService.submit(() -> deleteVm("c", "d"));