How can I call methods simultaneously in Java?
Make use of multiple threads, although you should read up on concurrency if you're going to edit the same objects from multiple threads.
public static void main(String[] args) {
new Thread() {
public void run() {
method1();
}
}.start();
new Thread() {
public void run() {
method2();
}
}.start();
//etc
//or, as kingdamian42 pointed out, if you use java8, use this
new Thread(() -> method1()).start();
new Thread(() -> method2()).start();
}
how to call methods in java simultaneously?
Don't conflate game time with CPU time. Just because players move at the same game time doesn't mean you need to have CPU threads executing concurrently. You just need a logic loop that simulates simultaneous movement.
For example, loop over all the players and check that their actions don't conflict with each other. If two players want to move to the same location, show an error. Otherwise, loop over them a second time and move them all to their new locations. Then redraw the scene. Even though you're updating the players one at a time in the second loop, the screen won't show the movements until the entire scene is repainted.
How to run 2 methods concurrently in same class with Java
There are several ways to achieve your task. You have quiet easy situation when threads should not be synchronized.
You can use ExecutorService
from Java Concurrency:
public class ConcurrentCode {
private int countA = 0;
private int countB = 0;
int countA(){
for (int i = 0; i < 1000; i++) {
countA++;
}
System.out.println(countA);
return countA;
}
int countB(){
for (int i = 0; i < 1000; i++) {
countB++;
}
System.out.println(countB);
return countB;
}
public void execute(){
ExecutorService executorService = Executors.newFixedThreadPool(2);
// method reference introduced in Java 8
executorService.submit(this::countA);
executorService.submit(this::countB);
// close executorService
executorService.shutdown();
}
public static void main(String[] args){
new ConcurrentCode().execute();
}
}
Remember to shutdown ExecutorService
otherwise your application won't stop because it will have alive threads.
Or you can have the simplest approach using vanilla Java threads:
public void executeInNativeThreads(){
// starts new thread and executes countA in it
new Thread(this::countA).start();
// starts new thread and executes countB in it
new Thread(this::countB).start();
}
To get computation results you can get the Future<Integer>
from executorService
and then you have a choice:
- poll
Future
if it is done - wait until the
Future
will be completed. - wait explicitly for a certain timeout
Here is an example:
public void execute() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<Integer> future1 = executorService.submit(this::countA);
Future<Integer> future2 = executorService.submit(this::countB);
// wait until result will be ready
Integer result1 = future1.get();
// wait only certain timeout otherwise throw an exception
Integer result2 = future2.get(1, TimeUnit.SECONDS);
System.out.println("result1 = " + result1);
System.out.println("result2 = " + result2);
executorService.shutdown();
}
Note, while we are explicitly waiting for result of future1
, future2
is still being executed in another thread. It means that there won't be big delay in computation of future2
in particularly this example.
Also, take a look at CompletionStage which is used in asynchronous computations.
How to execute the same method concurrently in Java
If you want call method concurrently you need threads. Java documentation for concurrency: https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html.
You have many options how to create/use threads in java.
1)
if you know how many threads do you need you can create threads manually like this:
Thread thread1 = new Thread(()->deleteVm("a","b");
Thread thread2 = new Thread(()->deleteVm("c","d");
//START the threads
thread1.start();
thread2.start();
2)
you can use default threads pool(usually thread per cpu core) like this:
CompletableFuture.runAsync(() -> deleteVm("a", "b"));
CompletableFuture.runAsync(() -> deleteVm("c", "d"));
3)
you can create your own thread executor like this
ScheduledExecutorService executorService = Executors.nScheduledExecutorService executorService = Executors.newFixedThreadPool(5)
executorService.submit(() -> deleteVm("a", "b"));
executorService.submit(() -> deleteVm("c", "d"));
How to call multiple methods at same time?
In order to run all three methods concurrently you can use Executor
to run concurrent threads, and wait for the result thanks to Future
. Something like:
Executor executor = Executors.newFixedThreadPool(3);
Future<List<Student>> studentsFuture = executor.submit(() -> return studentMao.getAll(collegeId));
Future<List<Department>> departmentsFuture = executor.submit(() -> return departmentsMao.getByCollegeId(collegeId));
Future<List<College>> collegesFuture = executor.submit(() -> return collegeMao.getByUniversityId(universityId));
List<Student> students = studentsFuture.get();
List<Department> departments = departmentsFuture.get();
List<College> colleges = collegesFuture.get();
Get waits until the current task running in another threads finishes, so this piece of code will finish when all the concurrent threads have finished.
how to call a method with multiple threads
if you need simultaneous execution and each time new thread you can find the solution here
public class SleepClass {
public static void main(String[] args) {
SleepClass s= new SleepClass();
s.m2(500);
s.m2(1000);
}
public void m2(int time) {
SleepClass s= new SleepClass();
new Thread(() -> {
s.m1(time);
}).start();
}
public void m1(int time) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Spring boot execute 2 methods simultaneously
If you make your search
methods async, either using thread executors pool, or @Async
, you will be able to invoke them at once, and gather results after finish.
Just remember, that you will have to use Future
for this.
So something like this will be
@Async
public Future<List<Whatever>> search(whatever here){
resultList=whateverYouDoThere();
return new AsyncResult<Whatever>(resultList);
}
in both services ofc, and invocations:
List<Whatever> completeList=new ArrayList():
Future<Whatever> fut1=service1.search(...);
Future<Whateva> fut2=service2.search(...);
completeList.addAll(fut1.get());
completeList.addAll(fut2.get();
//here you got all the stuff in completeList
I skipped your case here as I was too lazy to read it carefuly, so in your case it would be
Future<SearchResult1> fut1=service1.search(params);
Future<SerchResult2> fut2 = service2.search(params);
model.addAttribute("list1", fut1.get());
model.addAttribute("list2", fut2.get());
or something very similar
Related Topics
Prevent Multiple Login Using the Same User Name and Password
Null Pointer on an Autowired Bean Which Is Not Mocked by Mockito
How to Get Summation of Pair(Key) Values in a Map in Java
Set Zoom Level to 100% in Selenium Webdriver When Default Is Not 100
How to Mock a Generic Parameter for a Unit Test in Java
How to Make Multiple Line String to Single Line String
How to Return a Select Query from JPA Repository With Foreign Key Type
How to Test a Void Method Using Junit And/Or Mockito
How to Solve the "Failed to Lazily Initialize a Collection of Role" Hibernate Exception
Alternative to Switch Case in Java
Regular Expression for Uppercase Letters in a String
Java: How to Print Array Without Square Brackets and Commas
Spring Rest Post Json Requestbody Content Type Not Supported
Spring Boot - Post Method Not Allowed, But Get Works
How to View Apache Parquet File in Windows
The Package Org.W3C.Dom Is Accessible from More Than One Module: <Unnamed>, Java.Xml
How to Prevent Xss Attacks or Untrusted Data in Rest API Json Using Java