简体   繁体   English

Java MultiThreading代码错误

[英]Java MultiThreading Code Error

I am trying to learn multithreading concepts in Java. 我正在尝试用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 ? 任何人都可以帮我解决这个问题吗?

In

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

you are creating anonymous inner class that extends Thread class. 您正在创建扩展Thread类的匿名内部类。 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访问权限,则必须使其最终成为

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() . 为此,调用他们的start()方法,如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 如果你不想将方法的局部变量声明为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());
        }
    }
}

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. 最好使用Runnable并将其传递给线程构造函数。

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. 除此之外,正如其他人所说,任何直接在匿名类中的变量都需要声明为final。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM