繁体   English   中英

如何在 Java 中创建动态线程

[英]How To Create Dynamic Threads in Java

我正在尝试学习如何由用户在控制台中创建指定数量的线程。 没有什么可以帮助我的,我想详细说明如何创建动态数量的线程。 我知道如何使用扫描仪将用户输入到程序中,但在创建线程方面需要帮助

我尝试使用这种方法,因为它对我来说最有意义(我是一个非常业余的程序员学习 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 方法。 它是 morethreads 类的一部分,因此该类需要实现 Runnable。

然后,您需要创建它的一个实例而不是 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();
>         }
>     } }

希望这可以帮助

试试下面的代码:

您需要实现 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();
        }
    }
}

希望这可以帮助!

暂无
暂无

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

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