Skip to Main Content

Adding a 2D Array using cooperative threads

User_AYF65Oct 28 2017 — edited Oct 28 2017

I am trying to add a 2D array using cooperative threads. But i am getting answer of only the last thread. I have 3 threads only. My code is:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

public class Arr2DThreadAdd {

static int[ ] [ ] arr2D ={{10, 20, 30, 40}, {11, 12, 13, 14}, {12, 13, 14, 15}};

static int[ ] result = new int[3];

static class job extends Thread{

    int arr2Mindex;

    job(int index){

      arr2Mindex= index;    

   }

    public void run(){

       int i;

       int sum=0;

      

      

        for( i=0;i<4; ++i)

            sum = sum +arr2D[arr2Mindex][i];

       

        result[arr2Mindex]= sum;

           

    }

}

/**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

        job[] obj = new job[3];

        for(int i=0; i<3; ++i){

            obj[i]= new job(i);

            obj[i].start();

            try{

                obj[i].join();

            }catch (Exception e) {

                  e.printStackTrace();

             }

        }

    String res="";

  

   for( int j= 0; j<3; ++j)

      res = result[j] + " ";

   JOptionPane.showMessageDialog(null, res);

    }

}

Right now i am getting only 54 which is the correct answer for the last element of 2D array i.e. {12, 13, 14, 15}

When i checked the following line:
obj[i]= new job(i);
by passing values like
obj[i]= new job(0);
or
obj[i] = new job(1);
I am getting zero in both the above cases. However when i typed:
obj[i] = new job(2);

I got 54.

Somebody please guide me what is the problem in my code.

Zulfi.

This post has been answered by User_AYF65 on Oct 28 2017
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked due to inactivity on Nov 25 2017
Added on Oct 28 2017
1 comment
358 views