gpt4 book ai didi

java - 如何使用如下所示的线程获取输出?

转载 作者:行者123 更新时间:2023-12-01 23:10:14 25 4
gpt4 key购买 nike

import java.util.Scanner;
class CubaThread extends Thread {
public CubaThread (String s) {
super(s);
}
public void run() {
int num;
Scanner sc = new Scanner(System.in);
System.out.println("Enter +ve number: ");
num = Integer.parseInt(sc.nextLine());
for (int i=1;i<5;i++){
System.out.println("Olla I am "+getName()+i);
try{
Thread.sleep(10);
}
catch(InterruptedException e){
}
}
}
}
public class Cuba{
public static void main(String args[]){
new CubaThread("Thread #").start();
}
}

下面是我想要的输出:

Enter +ve number:
4

Hello, I am Thread #1

Hello, I am Thread #4

Hello, I am Thread #2

Hello, I am Thread #3

这是我实际得到的:

Enter +ve number:
4

Hello, I am Thread #1

Hello, I am Thread #2

Hello, I am Thread #3

Hello, I am Thread #4

最佳答案

您需要让每个线程执行相同的任务,并且仅在线程之间更改名称,如下所示:

class CubaThread extends Thread { 
public CubaThread (String s) {
super(s);
}
public void run() {
try {
Thread.sleep(10);
}
catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("Olla I am "+getName());
}
public static void main(String args[]) {
System.out.println("Enter +ve number: ");
Scanner sc = new Scanner(System.in);
// you can declare num on the same line that it is initialized
int num = Integer.parseInt(sc.nextLine());
for(int i = 0; i < num; i++)
new CubaThread("Thread #"+i).start();
}
}

输入示例:

Enter +ve number:
4

示例输出:

Olla I am Thread #2
Olla I am Thread #0
Olla I am Thread #3
Olla I am Thread #1

关于java - 如何使用如下所示的线程获取输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58380717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com