0

I have one task which should be done by two thread at the same time.I am going to send one array to both threads to calculate something (For example thread 1 should check half of array and return result and thread two should check the other half and return result) and I want to add the result of both threads as final result in my main

class loop1 extends Thread {
    int sum1 = 0;
    ArrayList < Integer > list;
    public loop1(ArrayList < Integer > lis) {
        this.list = list;
    }
    public void run() {
        try {
            for (int i = 0; i < list.size() / 2; i++) {
                sum1 += lis.get(i);
            }
        } catch(Exception e) {}
    }
    return sum1;
}

class loop2 extends Thread {
    int sum2 = 0;
    ArrayList < Integer > list;
    public loop1(ArrayList < Integer > lis) {
        this.list = list;
    }
    public void run() {
        try {
            for (int i = lis.size() / 2; i < list.size(); i++) {
                sum1 += lis.get();
            }
        } catch(Exception e) {}
    }
    return sum2;
}

class check {
    public static void main(String[] args) {
        ArrayList < Integer > list = new ArrayList < >();
        loop1 loop1 = new loop1(lis);
        loop2 loop2 = new loop2(list);
        loop1.start();
        loop2.start();
        int sum = sum1 + sum2;
        System.out.print(sum);
    }
}
ug_
  • 11,267
  • 2
  • 35
  • 52
Ashkan
  • 49
  • 6
  • The code you've posted is pretty much illegible. Can't even format it. Please make sure it compiles and format your code. – ernest_k Feb 10 '19 at 06:53
  • declare your sum1 and sum2 as `static AtomicInteger`. but you never get what you expect. you need to await the each thread's result. read this article - https://stackoverflow.com/questions/289434/how-to-make-a-java-thread-wait-for-another-threads-output – dgregory Feb 10 '19 at 07:07
  • how can I use the result of each thread in main ? – Ashkan Feb 10 '19 at 07:09
  • @ernest_k : it is not my complete code so I just mentioned as an example , but my purposes are 2 things >> 1. send same value from main to 2 threads and 2. return the result from each thread to main so if you have any idea please let me know – Ashkan Feb 10 '19 at 07:32
  • @Ashkan I formatted your code, but in the future be sure to provide at minimum formatted or hopefully code that can be compiled. You will greatly increase your chances of getting assistance that way. – ug_ Feb 10 '19 at 08:13

1 Answers1

1

Main points

Threads are started not in the same way they were running.

loop1.start();
loop2.start();
// here you should check that both loop1 and loop2 thread has been finished
int sum = loop1.sum1 + loop2.sum2;

Using ExecutionService and Feature

public class Check {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        int[] arr = createArray(100);

        Future<Integer> task1 = calculate(arr, 0, arr.length / 2, pool);
        Future<Integer> task2 = calculate(arr, arr.length / 2, arr.length, pool);

        while (!task1.isDone() || !task2.isDone()) {
            Thread.sleep(300);
        }

        System.out.println(task1.get() + task2.get());
    }

    private static int[] createArray(int length) {
        int[] arr = new int[length];

        for (int i = 0; i < arr.length; i++)
            arr[i] = i;

        return arr;
    }

    private static Future<Integer> calculate(final int[] arr, final int fromInclusive, final int toExclusive, ExecutorService pool) {
        return pool.submit(() -> {
            int sum = 0;

            for (int i = fromInclusive; i < toExclusive; i++)
                sum += arr[i];

            return sum;
        });
    }
}

Using class Thread

public class Check {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int[] arr = createArray(100);
        Task task1 = new Task(arr, 0, arr.length / 2);
        Task task2 = new Task(arr, arr.length / 2, arr.length);

        task1.start();
        task2.start();

        task1.join();
        task2.join();

        System.out.println(task1.getSum() + task2.getSum());
    }

    private static int[] createArray(int length) {
        int[] arr = new int[length];

        for (int i = 0; i < arr.length; i++)
            arr[i] = i;

        return arr;
    }

    private static final class Task extends Thread {
        private final int[] arr;
        private final int fromInclusive;
        private final int toExclusive;
        private int sum;

        public Task(int[] arr, int fromInclusive, int toExclusive) {
            this.arr = arr;
            this.fromInclusive = fromInclusive;
            this.toExclusive = toExclusive;
        }

        public int getSum() {
            return sum;
        }

        @Override
        public void run() {
            for (int i = fromInclusive; i < toExclusive; i++)
                sum += arr[i];
        }
    }
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35