gpt4 book ai didi

Java多线程代码错误

转载 作者:行者123 更新时间:2023-12-02 07:40:11 26 4
gpt4 key购买 nike

我正在尝试学习 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 类的匿名内部类。你一定知道,那个匿名内部类have access only to final local variables它们是创建的方法的,因此如果您想访问 int [] arr 您必须将其设置为最终的

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

您还创建了线程,但没有启动它们。为此,请调用 start() 方法,例如 thread1.start()

<小时/>

如果你不想将方法的局部变量声明为final,你应该考虑创建线程,而不是作为匿名内部类,而是作为单独的类,例如

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());
}
}
}

关于Java多线程代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11713943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com