#Threads

1 messages · Page 1 of 1 (latest)

patent mauve
#

I want to create a class DisplayChar, which creates 16 threads and waits for it to finish. Every thread returns a different letter and should be returned 100 times.

I tried to use an array in which I save all threads, start them and then wait for them to finish with "join".
I know that I am doing this wrong, but how can I fix this? How can I use a for-loop to count up the letter and at the same time use a for-loop to create and start the threads?

    String letter;
    int n; 
    
    //constructor
    DisplayChar(String Letter, int N){  
        this.letter= Letter;
        this.n = N;
    }

    public void run() {
        for (int i= 1; i<=n; i++) {
        System.out.println(""+i+letter);
        System.out.flush();
        }
        }

    public static void main(String[] args) {
              Thread threads[] =  new Thread[16];
             for (char x = 'a'; x <= 'p'; x++) { 
              for (int j = 0; j < threads.length; j++) {
                threads[j] = new Thread (new DisplayChar( ""+x, 100));
              }            
                threads[j].start();
        }
                for (int j = 0; j < threads.length; j++) {
            try {
                threads[j].join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        }
                }
viral mistBOT
#

Hey, @patent mauve!
Please remember to /close this post once your question has been answered!

undone maple
#

when creating the thread, you are passing a copy of the letters

#

or what's your problem?

patent mauve
#

sry I have edit the code - the problem is, that the letter get returns 16 times and not just 1 time (when using 1 for n)

#

when 100 is getting used for n, then the letter get returned 1600 times

#

There is a mistake at the for-loops:

              for (int j = 0; j < threads.length; j++) {```
But I don't know how to count up the letter and at the same time create the 16 threads. At the moment the letter gets count up and the same letter get returned 16 times - because I want to create 16 threads with `for (int j = 0; j < threads.length; j++) {`
undone maple
#

so everything will be executed 16 times

patent mauve
#

Is this is a solution for the problem? Or do I miss something?

      for (char x = 'a'; x <= 'p'; x++) {                 
              threads[d] = new Thread (new DisplayChar( ""+x, 3, counter));
           // DisplayChar r = new DisplayChar( ""+x, 100, counter);
              d++;
      }
              for (int j = 0; j < threads.length; j++) {    
              threads[j].start();
      } ```