多线程如何在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();
}
}
}
# 1 楼答案
看起来您正在尝试在多个线程中运行run方法。它是morethreads类的一部分,因此该类需要实现Runnable
然后需要创建它的实例,而不是线程
希望这有帮助
# 2 楼答案
尝试以下代码:
您需要实现run方法
希望这有帮助