简体   繁体   English

如何使用如下线程获取 output?

[英]How to get output using thread like below?

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();
    }
}

Below is the output I want:下面是我想要的 output:

Enter +ve number:
4

Hello, I am Thread #1

Hello, I am Thread #4

Hello, I am Thread #2

Hello, I am Thread #3

Here's what I'm actually getting:这是我实际得到的:

Enter +ve number:
4

Hello, I am Thread #1

Hello, I am Thread #2

Hello, I am Thread #3

Hello, I am Thread #4

You need to have each thread do the same task, and only have the name change between the threads, like so:您需要让每个线程执行相同的任务,并且只在线程之间更改名称,如下所示:

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();
  }
}

Example input:示例输入:

Enter +ve number:
4

Example output:示例 output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用线程同步方法进行如下打印? - How Can I print like below using thread synchronization method? 如何更正以下代码以按预期获得 output? - How to correct the below code to get output as expected? 我如何获得 output 之类的 output 字符串? - How I get the output like output string? 当数据如下所示时,如何从改造中获取数据 - How to get data from retrofit when data is like this as given below 如何为不同的 API 获取不同的参数,如下所述 - How to get different parameters for different APIs like mentioned below 如何实现类似于尝试获取值的东西,如果为null,则在不使用Thread.sleep的情况下稍微睡一会儿? - How to implement something like Try to get a value, if null then sleep a little without using Thread.sleep? 在以下情况下,如何迭代向量的向量并获得输出? - How to iterate the vector of vectors and get the output in the below scenario? 如何在执行分页等线程时获取回调 - how to get callback while executing thread like paging 在以下情况下建议使用Thread.sleep() - Is using Thread.sleep() advisable in the below scenario 如何使用线程ID在Java中获取线程运行时间? - How to get the thread running time in java using thread ID?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM