Java 多线程传值问题
在开发过程中遇到了向多线程传值的问题,一般来说,可以直接将所要传递的参数设置为final(常量)即可:
final String hello= "hello world!";
new Thread() {
@Override
public void run() {
System.out.println(hello);
}
}.start();
输出:
hello world!
但是当所要传递的参数是需要变化的,需要遍历数组获取时,就会有错误发生:
String[] arr = ["hello", "world"];
for(int i = 0; i<arr.length;i++){
final String hello= arr[i];
new Thread() {
@Override
public void run() {
System.out.println(hello);
}
}.start();
}
输出:
hello
hello
此时因为设置了final,导致常量无法被修改值,所以输出的都是相同字段,此时的解决方法就是:重写Thread类,內建一个属性,在构造函数中传值即可:
class MyDownloadThread extends Thread {
public String finalTmp;
public MyDownloadThread(String tmp) {
this.tmp= tmp;
}
@Override
public void run() {
System.out.println(tmp);
}
}
调用时直接传值:
String[] arr = ["hello", "world"];
for(int i = 0; i<arr.length;i++){
new MyDownloadThread(arr[i]).start();
}
输出:
hello
world