Reputation: 1
Ok so my issue is that I have an array of threads, let's say 12 Threads and this is my code of my main method.
public static void main(String[] args){
Thread[] threads = new Thread[Integer.parseInt(args[0])];
System.out.println(Integer.parseInt(args[0]));
for(int i = 0; i < threads.length; i++){
threads[i] = new ThreadNumber();
threads[i].start();
}
}
Then how do I implement a constructor that helps me give every Thread a number so that I have a variable for my run method where I can print it.
static class ThreadNumber extends Thread{
// public ThreadNumber(){
// nummer +=1;
// }
public void run(){
if(getName().substring(7).equals("0")){
// System.out.println("No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall.");
}
else if(getName().substring(7).equals("1")){
//System.out.println("1 bottle of beer on the wall, 1 bottle of beer. Take one down and pass it around, no more bottles of beer on the wall.");
}
else if(getName().substring(7).equals("2")){
// System.out.println("2 bottles of beer on the wall, 2 bottles of beer. Take one down and pass it around, 1 bottle of beer on the wall.");
}
else{
// System.out.println(getName().substring(7) + " bottles of beer on the wall, " + getName().substring(7) + " bottles of beer. Take one down and pass it around, " + (Integer.parseInt(getName().substring(7)) - 1) + " bottles of beer on the wall.");
}
}
}
For this example it still works with using the getName method of the Thread class but if I implement Runnable instead of Thread then it doesnt work anymore and I think it only works with a constructor.
Upvotes: 0
Views: 190
Reputation: 202
You can do it using static
keyword. So your constructor will look like this:
private static int n;
public ThreadNumber() {
setName(String.valueOf(++n));
}
P.S. String.valueOf()
is using, because setName()
accepts string only.
Upvotes: 1