Using Runnable to run a method by multiple threads
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Using Runnable to run a method by multiple threads

  1. #1
    Join Date
    May 2017
    Posts
    1

    Using Runnable to run a method by multiple threads

    In my program, I want to create multiple threads in one of the methods where each thread has to run a specific method with a given input. Using Runnable, I have written this snippet.

    Code:
    class myClass {
      public myClass() { }
      public void doProcess() {
        List< String >[] ls;
        ls = new List[2];  // two lists in one array
        ls[0].add("1");  ls[0].add("2");  ls[0].add("3");
        ls[1].add("4");  ls[1].add("5");  ls[1].add("6");
    
        // create two threads 
        Runnable[] t = new Runnable[2]; 
        for (int i = 0; i < 2; i++) {
          t[ i ] = new Runnable() {
            public void run() {
              pleasePrint( ls[i] );
            }
          };
          new Thread( t[i] ).start();
        }
      }
      void pleasePrint( List< String > ss )
      {
        for (int i = 0; i < ss.size(); i++) {
          System.out.print(ss.get(i)); // print the elements of one list
        }
      }
    }
    
    public class Threadtest {
      public static void main(String[] args) {
        myClass mc = new myClass();
        mc.doProcess();
      }
    }
    Please note, my big code looks like this. I mean in one method, doProcess(), I create an array of lists and put items in it. Then I want to create threads and pass each list to a method. It is possible to define the array and lists as private class members. But, I want to do that in this way.

    Everything seems to be normal, however, I get this error at calling pleasePrint():

    Code:
    error: local variables referenced from an inner class must be final or effectively final
          pleasePrint( ls[i] );
    How can I fix that?

  2. #2
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,741

    Re: Using Runnable to run a method by multiple threads

    variables referenced from an inner class must be final or effectively final
    Did you try making ls final? What happened?
    Norm

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This a Codeguru.com survey!


On-Demand Webinars (sponsored)