简体   繁体   中英

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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