Reputation: 3858
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 ?
Upvotes: 0
Views: 109
Reputation: 11805
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.
Upvotes: 0
Reputation: 124225
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());
}
}
}
Upvotes: 2