简体   繁体   English

如何在 Java 中创建动态线程

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

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

It looks like you are trying to run the run method in multiple threads.看起来您正在尝试在多个线程中运行 run 方法。 It is part of the morethreads class so this class needs to implement Runnable.它是 morethreads 类的一部分,因此该类需要实现 Runnable。

You then need to create an instance of it instead of Thread.然后,您需要创建它的一个实例而不是 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希望这可以帮助

Try the following code:试试下面的代码:

You need to implement the run method.您需要实现 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();
        }
    }
}

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM