[英]Java - Creating Multiple Threads with a For Loop
我正在嘗試創建多個線程,其數量取決於命令行的輸入。 我知道擴展 Thread 不是最好的 OO 實踐,除非您正在制作 Thread 的專門版本,但假設這段代碼創建了所需的結果?
class MyThread extends Thread {
public MyThread (String s) {
super(s);
}
public void run() {
System.out.println("Run: "+ getName());
}
}
class TestThread {
public static void main (String arg[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please input the number of Threads you want to create: ");
int n = input.nextInt();
System.out.println("You selected " + n + " Threads");
for (int x=0; x<n; x++)
{
MyThread temp= new MyThread("Thread #" + x);
temp.start();
System.out.println("Started Thread:" + x);
}
}
}
ExecutorService有更好的選擇
示例代碼:
import java.util.concurrent.*;
public class ExecutorTest{
public static void main(String args[]){
int numberOfTasks = Integer.parseInt(args[0]);
ExecutorService executor= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
try{
for ( int i=0; i < numberOfTasks; i++){
executor.execute(new MyRunnable(i));
}
}catch(Exception err){
err.printStackTrace();
}
executor.shutdown(); // once you are done with ExecutorService
}
}
class MyRunnable implements Runnable{
int id;
public MyRunnable(int i){
this.id = i;
}
public void run(){
try{
System.out.println("Runnable started id:"+id);
System.out.println("Run: "+ Thread.currentThread().getName());
System.out.println("Runnable ended id:"+id);
}catch(Exception err){
err.printStackTrace();
}
}
}
用法:
java ExecutorTest 2
Runnable started id:0
Run: pool-1-thread-1
Runnable ended id:0
Runnable started id:1
Run: pool-1-thread-2
Runnable ended id:1
相關帖子:(使用ExecutorService
作為替代普通Thread
優點)
是的,它正在創建和啟動n
線程,所有線程都在打印Run:
和它們的名稱后立即結束。
java JVM 一次可以創建 20000 個線程的一件重要事情。 在 Java 中創建 255 個線程
class MyThread1 extends Thread {
int k;
public MyThread1(int i) {
k = i;
}
@Override
public void run() {
//Your Code
System.out.println("Thread no. "+k);
}
}
class MainClass {
public static void main(String arg[]) throws UnknownHostException {
Refresh() ;
}
public static void Refresh(){
//create 255 Thread using for loop
for (int x = 0; x < 256; x++) {
// Create Thread class
MyThread1 temp = new MyThread1(x);
temp.start();
try {
temp.join(10);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
另一個使用 @ravindra-babu 推薦的 ExecutorService 的簡單示例
class MyRunnable implements Runnable{
int id;
public MyRunnable(int i){
this.id = i;
}
public void run(){
try{
long init = System.currentTimeMillis();
System.out.println("Start of Thread ID = " + id);
Thread.sleep(id * 1000);
long end = System.currentTimeMillis();
long elapsedTime = end - init;
System.out.println("Elapsed time of Thread ID " + id + ": " + elapsedTime);
} catch(Exception err){
err.printStackTrace();
}
}
}
然后你需要做的就是在循環內創建一個新線程
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
try{
ExecutorService executor= Executors.newFixedThreadPool(1);
executor.execute(new MyRunnable(i));
executor.shutdown();
} catch(Exception err){
err.printStackTrace();
return;
}
}
}
Java中的多線程:讓我們討論一下Java中的多線程嗎?
Java為多線程程序提供了內置支持。 多線程程序包含兩個或多個可以同時運行的部分。 此類程序的每個部分都稱為線程,每個線程定義單獨的執行路徑。 因此,多線程是多任務的專用形式。
多線程使您可以編寫非常高效的程序,從而可以最大限度地利用CPU,因為可以將空閑時間降到最低。 這對於Java在其中運行的交互式網絡環境特別重要,因為空閑時間很常見。
一個程序可以分為許多小程序。 每個小進程都可以作為單個線程處理(輕量級進程)。 多線程程序包含兩個或多個可以同時運行的線程。 這意味着一個程序可以同時執行兩個或多個任務。 例如,一個線程正在將內容寫入文件,而另一個線程正在執行拼寫檢查。
要創建新線程,請使用擴展Thread或實現Runnable接口的程序。 要知道,如何創建線程以及創建線程的可用方式以及線程的生命周期是什么,請閱讀以下文章:
多線程的優點: -多線程減少了計算時間。 因為它一次運行多個線程。 -它提高了應用程序的性能。 -線程分配相同的地址空間,從而節省了內存空間。 -線程之間的上下文切換通常比進程之間的開銷少。 -線程之間的通信成本相對較低。
在Java中創建多個線程:到目前為止,我們僅使用了兩個線程:主線程和單子線程。 但是,您的程序可以生成所需數量的線程。 例如,以下程序創建三個子線程。 主線程開始其所有子線程的工作,上下文切換將在這些線程之間完成。
//Create multiple threads
Class NewThread implements Runnable
{
String name;
Thread t;
NewThread(String threadname)
{
name=threadname;
t=new Thread(this,name);
System.out.println(“new thread:”+t);
t.start(); //start the thread
}
//This is the entry point of the thread
public void run()
{
try
{
for(int i=5;i>0;i++)
{
System.out.println(name+”:”+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name+”existing”);
}
}
Class multithreaddemo
{
Public static void main(String agrs[])
{
newThread(“one”);//start thread
new NewThread(“two”);
new NewThread(“three”);
try
{
// wait for the other thread to end
Thread.sleep(10000);
}
catch(interruptedException e)
{
System.out.println(“main thread interrupted”);
}
System.out.println(“main thread existing”);
}
}
該程序的輸出如下所示:new thread:thread [one,5,main]
新線程:thread [two,5,main]
新線程:thread [three,5,main]
一:5
2:5
三:5
一:4
2:4
三:4
一:3
2:3
三:3
一:2
2:2
三:2
一對一
2:1
三:1
現有一個
現有兩個
現有三個
現有主線程
Java多線程的主要概念:在使用Java多線程程序時,您應該了解以下因素:
1. 線程同步。
2.如何處理線程間通訊。
3. 什么是死鎖,如何處理 ?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.