Matt Henderson
Matt Henderson

Reputation: 11

Java passing value to new object

Is it possible to pass the value for i into the new thread object?

Current code:

int cores = 4;
final int n = 10000;
static double sum = 0.0;

Thread[] threads = new Thread[cores];

for (int i = 0; i < cores; i++)
{
    threads[i] = new Thread(new Runnable() {
        public void run() {
            for (int j = i * (n / cores); j < (i + 1) * N / P; j++) {
                double x = (j + 0.5) * step;
                sum += 4.0 / (1.0 + x * x);
            }
        }
    });
}

Regards

Upvotes: 0

Views: 66

Answers (2)

rgettman
rgettman

Reputation: 178243

Create your own inner class that extends Thread, then pass in your value to an instance of that class however you want - a constructor, a setter method, etc.

Here's starter code using a constructor.

public class MyThread extends Thread
{
   private int myI;

   public MyThread(int i) { myI = i; }

   @Override
   public void run()
   {
      // Your code goes here, referencing the "myI" variable.
   }
}

Upvotes: 1

Cyrille Ka
Cyrille Ka

Reputation: 15538

The minimal change of code that would solve your problem is to add a variable like index below, with the final modifier:

for (int i = 0; i < cores; i++)
{
    final int index = i; // put value of "i" into a final variable
    threads[i] = new Thread(new Runnable() {
        public void run() {
            // use "index" instead of "i"
            for (int j = index * (n / cores); j < (index + 1) * N / P; j++) {
                double x = (j + 0.5) * step;
                sum += 4.0 / (1.0 + x * x);
            }
        }
    });
}

Variables with final modifier are guaranteed not to change and therefore can be used in instances of anonymous classes.

Upvotes: 0

Related Questions