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