HowbeitGirl
HowbeitGirl

Reputation: 591

Multithreading Array Content?

This is to contribute towards a college assignment. I was just wanting some input if this is on the right track or not. The assignment calls for the use of multiple threads to add the array content. This is what I deducted is accurate, but again, I am unsure. Any advice or input would be fantastic. :)

I do not know if this is on the right track or not, so I was hoping for some expertise critique.

import java.util.*;

public class threadtest1 extends Thread
{
    int sum, sum2;
    int N = 5;

    int [] array = {1,3,2,4,5,6,7,8,9,10};
    int [] temp = new int [N];

    public static void main (String[] args)
    {
        threadtest1 run = new threadtest1();
        run.go();
    }

    public void go()
    {
        threadtest1 t1 = new threadtest1();
        threadtest1 t2 = new threadtest1();
        threadtest1 t_Total = new threadtest1();


        //To seperate and calculate the array by thread:        


        /****   FOR  THREAD 1    ****/
        t1.start();
        temp = Arrays.copyOfRange(array, 1,5);
        System.out.println("Temp : " + temp.length);

        for (int j = 0; j < temp.length; j++)
            {
                //sum = temp.get(i);
                sum += sum + j;
                System.out.println("T1 : " + sum);
            }

        /****   FOR  THREAD 2    ****/
        t2.start();
        temp = Arrays.copyOfRange(array, 6, 10);

        for (int k = 0; k < temp.length; k++)
        {
            //sum = temp.get(i);
            sum2 += sum2 + k;
            System.out.println("T2 : " + sum2);
        }

        /****   FOR  THREAD_TOTAL    ****/
        t_Total.start();
        sum = sum + sum2;
        System.out.println("T_Total: " + sum);
    }

}

Upvotes: 0

Views: 63

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

No, you're not on the right track at all. When you start a thread, its run() method is executed (in a separate thread). By default, the run() method does nothing. And you haven't overridden this method. So you're starting two threads that do nothing, and are executing the computation over the array in the main thread.

You should re-read the Java concurrency tutorial.

Upvotes: 4

Related Questions