Big Moe Pasha
Big Moe Pasha

Reputation: 59

How To Create Dynamic Threads in Java

I am trying to learn how to create a specified number of threads by the user in the console . There is not much to help me on and would like a detailed description on how to create a dynamic amount of threads. i know how to get the users input into a program using scanner but need help with the thread creation

i have tried to use this method as it makes the most amount of sense to me (i am a very amateur programmer studying CS):How to create threads dynamically?

my code

package threads;

 public class morethreads {
   public Runnable MyRunnable;
       public void run() {
        for (int i = 0; i<20; i++)
        System.out.println("Hello from a thread!" + i);
       }
    public void main(String args[]) {
    Thread[] hello = new Thread [10];//amount of threads
    for(int b =0; b < hello.length; b++){
        hello[b] = new Thread(MyRunnable);//<<this is the issue 
        hello[b].start();
     }
  }
}

Upvotes: 1

Views: 10749

Answers (2)

DarrenCibis
DarrenCibis

Reputation: 905

It looks like you are trying to run the run method in multiple threads. It is part of the morethreads class so this class needs to implement Runnable.

You then need to create an instance of it instead of Thread.

> public  class morethreads implements Runnable {
>     public void run() {
>         for (int i = 0; i<20; i++)
>             System.out.println("Hello from a thread!" + i);
>     }
>     public static void main(String args[]) {
>         Thread[] hello = new Thread [10];//amount of threads
>         for(int b =0; b < hello.length; b++){
>             hello[b] = new Thread(new morethreads());
>             hello[b].start();
>         }
>     } }

Hope this helps

Upvotes: 5

Ele
Ele

Reputation: 33726

Try the following code:

You need to implement the run method.

public class morethreads {
    public static Runnable MyRunnable = new Runnable() {
        public void run() {
            for (int i = 0; i<20; i++) {
                System.out.println("Hello from a thread!" + i);
            }
        }
    };

    public static void main(String args[]) {
        Thread[] hello = new Thread [10];//amount of threads
        for(int b =0; b < hello.length; b++) {
            hello[b] = new Thread(MyRunnable);//<<this is the issue 
            hello[b].start();
        }
    }
}

Hope this helps!

Upvotes: 0

Related Questions