Tell me how to pass the fillings of random numbers with the array arr to the stream, to calculate the amount ...

public class ff { public static void main(String[] args) throws InterruptedException { new Threard1().list(); long timer = -System.currentTimeMillis(); Runnable r1 = new Threard1(); Thread t1 = new Thread(r1); t1.start(); t1.join(); System.out.print("\n\n" + "mainSum: " + new Threard1().getSum()); timer += System.currentTimeMillis(); System.out.println("\n" + "Time: " + timer + "\n"); } 

}

 import java.util.Random; public class Threard1 implements Runnable{ private String title = "One"; private int delay=0; private int sizeArr=5; int sum; public int arr[] = new int[sizeArr]; public void list () { Random rand = new Random(); for (int i = 0; i < sizeArr; i++) { arr[i] = rand.nextInt(10); System.out.print("\n" + title + ": " + arr[i]); } } public void run() { for (int i = 0; i < sizeArr; i++) { sum = sum + arr[i]; } try { Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } } public int getSum () { return sum; } 

}

  • the instance created in new Threard1 (). list () is lost. Runnable r1 = new Threard1 (); creates a new instance. Obviously, it should be the same - AterLux

1 answer 1

First you need to decide in which class we need an array.

If for some reason in the future we need this array in the ff class, then we need to create an array in it. And then think about the transfer of this array. I would pass it using a constructor.

If you need to create an array in Threard1, then I would not create it as a separate method, but, let's say, would call its creation from the run method.

And in any case, you do not need to lose references to the object, because:

 new Threard1().list(); Runnable r1 = new Threard1(); Thread t1 = new Thread(r1); System.out.print("\n\n" + "mainSum: " + new Threard1().getSum()); 

These are 3 different copies with three different arrays.

In main, I would write like this:

 public static void main(String[] args) throws InterruptedException { long timer = -System.currentTimeMillis(); Threard1 threard1 = new Threard1(); Thread thread = new Thread(threard1); thread.start(); thread.join(); timer += System.currentTimeMillis(); System.out.println("=================="); System.out.println("mainSum: " + threard1.getSum()); System.out.println("Time: " + timer); } 

And in run () would add:

 this.list();