0

In Java, I have a code:

Graph[] graphs = new Graph[100];
for (int i = 0; i < 100; i++) {
    graphs[i] = new Graph();
    Graph g = graphs[i];
    g.subgraphs = new Graph[100 - i];
    g.leaves = new HashSet<Integer>();
    g.targets = new HashMap<Integer, int[]>(l - i);
    g.weights = new HashMap<Integer, Integer>(l - i);
}

I wish to write a parallel code. Could you please help me here learning Java threading. So I added this code:

Thread[] threads = new Thread[3];
for (int i = 0; i < threads.length; i++) {
    threads[i] = new Thread(new Runnable() {
        public void run() {
            // some code to run in parallel
        }
    });
    threads[i].start();
}

// as far as I understood this waits until threads above are finishing
for (int i = 0; i < threads.length; i++) {
    try {
        threads[i].join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Now I can copy the code from the loop when I create my custom Graph objects but I need to pass somehow an index i (which is from 0 to 100) to a run() method.

How can I do that?

0

3 Answers 3

2

If your objective is to maximize performance, then your best bet is almost certainly to do no parallelism at all here. Creating a few hundred HashMaps will almost certainly be cheaper than starting up any new threads.

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

Comments

1

In Java you can only reference final fields from anonymous inner classes, so you need declare an final variable j to access the index:

Thread[] threads = new Thread[3];
for (int i = 0; i < threads.length; i++) {
  final int j = i;
  threads[i] = new Thread(new Runnable() {
    public void run() {
      // some code to run in parallel
      System.out.println(j);
    }
  });
  threads[i].start();
}

Comments

1

I know multithreading is not suitable for instantiating objects, but I support you to practise coding skills personally. so just try it and learn from the real result.

Actually, since Java SE 1.5, low level multithreading code is rarely used. because the concurrent package comes up. try to learn from Executor, ExecutorService and CompletionService.

See Perform N tasks in parallel and Understanding java.util.concurrent.CompletionService

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.