1

I have this code:

public final class AClass{ static Long x=0; public static Long aMethod(args...){ //commands x = aMethod(args...); x += aMethod(args...); //commands } } 

I want to execute the two lines of code(the two calls of aMethod) parallel with threads.

4
  • What's stopping you? Commented Mar 25, 2017 at 23:14
  • Hi Justas, threads take as a parameter object and no methods.. Commented Mar 25, 2017 at 23:16
  • 1
    I suggest you start reading this from the start: docs.oracle.com/javase/tutorial/essential/concurrency Commented Mar 25, 2017 at 23:18
  • Oh please, this is a "Abstract" code , I hoped to understand the essence Commented Mar 25, 2017 at 23:25

1 Answer 1

1

This is a relatively simple problem and the following code should solve your predicament

Thread thread1 = new Thread() { public void run() { x = aMethod(args...); } }; Thread thread2 = new Thread() { public void run() { x += aMethod(args...); } }; thread1.start(); thread2.start(); 

Then you join the result with:

thread1.join(); thread2.join(); 

These 2 lines of code will throw an InterruptedException and will need to be handled with a try/catch

Sign up to request clarification or add additional context in comments.

4 Comments

That approach is not thread safe. If both threads modify the variable at the same time you could get undefined behavior. You can fix it by making x an AtomicLong. Alternatively you could also work with CompletableFuture.
Or you could use parallel streams. That would by far be the shortest way to write it.
Not a good solution. If thread2 finishes before thread1 then thread1 will overwrite the value in x.
If i make method synchronized?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.