有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程如何在Java中创建动态线程

我试图学习如何由用户在控制台中创建指定数量的线程。没有太多的帮助,我想详细介绍一下如何创建动态数量的线程。我知道如何让用户输入到一个程序使用扫描仪,但需要帮助创建线程

我尝试过使用这种方法,因为它对我来说最有意义(我是一个学习CS的业余程序员):How to create threads dynamically?

我的代码

包线

 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();
     }
  }
}

共 (2) 个答案

  1. # 1 楼答案

    看起来您正在尝试在多个线程中运行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();
    >         }
    >     } }
    

    希望这有帮助

  2. # 2 楼答案

    尝试以下代码:

    您需要实现run方法

    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();
            }
        }
    }
    

    希望这有帮助