0

I am trying to learn multithreading concepts in Java. I am stuck with error during execution of my code snippet.

My code snippet:

class ThreadDemo {
public static void main(String args[]) {
   try{

   int [] arr = new int[10] ;
      for(int i = 0 ; i < 10 ; i++)
         arr[i] = i ;

   for(int c =0 ; c < 2 ; c++){
         for(int i = 0 ; i < 3 ; i++) //I want to run it on one thread
             System.out.println(arr[i]);
         for(int j = 0 ; j < 5 ; j++)  //I want to run it on another thread
             System.out.println(arr[j]);
            }

} catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
   }
}

Now, to solve this I have tried,

class ThreadDemo {
public static void main(String args[]) {
try{

int [] arr = new int[10] ;
for(int i = 0 ; i < 10 ; i++)
arr[i] = i ;

    for(int c =0 ; c < 2 ; c++){
         Thread thread1 = new Thread () {
         public void run () {
         for(int i = 0 ; i < 3 ; i++) //I want to run it on one thread
           System.out.println(arr[i]);}
          };

          Thread thread2 = new Thread () {
          public void run () {
          for(int j = 0 ; j < 5 ; j++) //I want to run it on one thread
           System.out.println(arr[j]);}
          };


         }

} catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
   }
}

But gives error. Can anyone help me how to solve this ?

2 Answers 2

2

In

for (int c = 0; c < 2; c++) {
    Thread thread1 = new Thread() {//<- here

you are creating anonymous inner class that extends Thread class. You must know, that anonymous inner classes have access only to final local variables of method that they are created so if you want to gain access to int [] arr you must make it final like

final int[] arr = new int[10];

Also you created threads but you didn't start them. To do that invoke their start() method like thread1.start().


If you don't want to declare local variables of method as final you should consider creating threads not as anonymous inner classes but as separate classes for example

class MyThread extends Thread {
    int[] array;
    int iterations;

    public MyThread(int[] arr, int i) {
        array=arr;
        iterations = i;
    }

    @Override
    public void run() {
        for (int i = 0; i < iterations; i++)
            System.out.println(array[i]);
    }
}

class ThreadDemo {
    public static void main(String args[]) {
        try {

            int[] arr = new int[10];
            for (int i = 0; i < 10; i++)
                arr[i] = i;

            for (int c = 0; c < 2; c++) {
                MyThread thread1 = new MyThread(arr, 3);
                MyThread thread2 = new MyThread(arr, 5);
                thread1.start();
                thread2.start();
            }

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

It is not possible to use an shared array in two threads anyway ? Actually, I have many shared variables. If I make them final, I can't able to modify them. BTW, I didn't call them because it is giving error that "make arr final".
Local variables of method must be declared as final to be accessed by anonymous inner class. Fields of class don't have to be final so maybe this will be solution. You can also create Threads not as anonymous inner classes, but as separate classes or just inner classes (not declared in method) and pass local variables to them for example in constructor.
@Arpssss Check my edited answer. Maybe you will find something usefull :)
0

FYI: Extending Thread is not the best idea if you're not actually providing any additional logic to it. It's best to use a Runnable and pass it to the threads constructor.

Thread t = new Thread(new Runnable() {
    public void run() {
    }
});
t.start();

Aside from that, as someone else noted, any variables directly in an anonymous class need to be declared as final.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.