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

下面是我想要的 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

这是我实际得到的:

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

示例 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM