[英]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.