Java多线程代码错误
问题描述:
我想学习Java中的多线程概念。我在执行我的代码片段时遇到了错误。Java多线程代码错误
我的代码片段:
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());
}
}
}
现在,为了解决这个我已经试过了,
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());
}
}
}
但给人错误。任何人都可以帮我解决这个问题吗?
答
在
for (int c = 0; c < 2; c++) {
Thread thread1 = new Thread() {//<- here
要创建继承Thread类的匿名内部类。你必须知道,匿名内部类,他们创建的,因此,如果你想访问int [] arr
你必须让最终像
final int[] arr = new int[10];
而且你创建的线程,但你没有启动它们的方法have access only to final
local variables。要做到这一点,请调用他们的start()
方法,如thread1.start()
。
如果你不想申报方法的局部变量作为最终你应该考虑创建线程不是匿名内部类,但作为单独的类例如
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());
}
}
}
答
FYI:扩展线程不如果你实际上没有提供任何额外的逻辑,这是最好的想法。最好使用Runnable并将其传递给线程构造函数。
Thread t = new Thread(new Runnable() {
public void run() {
}
});
t.start();
除此之外,正如其他人指出的,任何直接在匿名类中的变量都需要声明为final。
无论如何,在两个线程中使用共享数组是不可能的?其实,我有很多共享变量。如果我让他们最终,我不能修改它们。顺便说一句,我没有给他们打电话,因为它给出了“做出决定”的错误。 – Arpssss 2012-07-30 00:15:03
'方法的局部变量'必须声明为'final'才能被匿名内部类访问。 '类的领域'不一定是最终的,所以也许这将是解决方案。你也可以创建线程不作为匿名内部类,但作为单独的类或只是内部类(不在方法中声明)并将局部变量传递给它们,例如在构造函数中。 – Pshemo 2012-07-30 00:26:18
@Arpssss检查我编辑的答案。也许你会发现一些有用的:) – Pshemo 2012-07-30 00:43:07