2

I am relativity new to multithreading in Java, and I would like to know if it is possible to execute a method within a class in parallel. So instead of this:

public void main() {
  this.myMethod();
  this.myMethod();
}

... where each method within the class is fired after the previous call has finished, that they would be done in parallel. I know the following example can be done, but that involves creating new classes, which I would like to avoid:

public class HelloRunnable implements Runnable {
  public void run() {
    System.out.println("Hello from a thread!");
  }

  public static void main(String args[]) {
    (new Thread(new HelloRunnable())).start();
  }
}

Just to be clear, I have seen this example, but it was of no help me to me.

Is the key to cracking this issue involve using public static methods? Either way, could someone please provide an example how to do this with their solution?

Thank you for your time!

2 Answers 2

4

Sorry, can't be done according to your restrictions. You can't run anything in a Java thread without creating a Thread object, and something to contain the run() method: either a separate class that implements Runnable, or a class that extends Thread. The question you pointed to shows exactly what to do; there's no "better" answer, nor indeed any other answer.

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

1 Comment

Ah... alright. Guess I'll just end up using a bit more code. :) Thanks, Ernest!
2

I'd probably do it like this. The CountDownLatch and Executors classes are handy utilities from Java 5 to make this kind of stuff easier. In this particular example the CountDownLatch will block main() until both parallel executions have completed.

(So to answer your question: it's even worse than you thought! You have to write even MORE code!)

ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool();

public void main() {
  final CountDownLatch cdl = new CountDownLatch(2); // 2 countdowns!
  Runnable r = new Runnable() { public void run() {
    myMethod();
    cdl.countDown();
  } };

  EXECUTOR_SERVICE.execute(r);
  EXECUTOR_SERVICE.execute(r);

  try {
    cdl.await();
  } catch (InterruptedException ie) {
    Thread.currentThread().interrupt();
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.