如何在 Java 中创建动态线程

Big*_*sha 1 java concurrency multithreading

我正在尝试学习如何由用户在控制台中创建指定数量的线程。没有太多可以帮助我的内容,并且希望详细描述如何创建动态数量的线程。我知道如何使用扫描仪将用户输入到程序中,但需要线程创建方面的帮助

我尝试使用这种方法,因为它对我来说最有意义(我是一个学习CS的非常业余的程序员):如何动态创建线程?

我的代码

封装线程;

 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();
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*bis 5

看起来您正在尝试在多个线程中运行 run 方法。它是 morethreads 类的一部分,因此该类需要实现 Runnable。

然后您需要创建它的实例而不是线程。

> 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();
>         }
>     } }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助