如何用构造函数给每个线程一个新编号



好的,我的问题是,我有一个线程数组,我们设为12个线程,这是我的主方法的代码。

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

那么我如何实现一个构造函数,帮助我给每个线程一个数字,这样我就有了一个变量,我的运行方法,我可以打印它。

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.");
}
}
}

对于这个例子,它仍然使用线程类的getName方法,但如果我实现Runnable而不是Thread,那么它不再工作,我认为它只与构造函数一起工作。

可以使用static关键字。所以你的构造函数看起来像这样:

private static int n;
public ThreadNumber() {
setName(String.valueOf(++n));
}

注:String.valueOf()正在使用,因为setName()只接受字符串。

相关内容

最新更新