java怎么设置线程名字
publicclassServer{inti=0;while(true){i++;Threadt=newThread(newMyExecute());t.currentT...
public class Server {
int i=0;
while (true) {
i++;
Thread t = new Thread(new MyExecute());
t.currentThread().setName("name"+i);
t.start();
}
class MyExecute implements Runnable {
public MyExecute() {}
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
}
我觉得打印出来应该是“name1”才对啊,可打印的是“Thread-0”,要怎么设置线程名字呢
搞定了,这样写就行了
Thread t = new Thread(new MyExecute(), "线程名"); 展开
int i=0;
while (true) {
i++;
Thread t = new Thread(new MyExecute());
t.currentThread().setName("name"+i);
t.start();
}
class MyExecute implements Runnable {
public MyExecute() {}
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
}
我觉得打印出来应该是“name1”才对啊,可打印的是“Thread-0”,要怎么设置线程名字呢
搞定了,这样写就行了
Thread t = new Thread(new MyExecute(), "线程名"); 展开
2个回答
展开全部
线程名要在线程中设置,即run()方法中,楼主的茄凯型写法是在设置main()方法颤猜的孙掘线程名,并非新建的线程名。代码改造一下:
public class Server {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
i++;
Thread t = new Thread(new MyExecute("name" + i));
t.start();
}
}
}
class MyExecute implements Runnable {
private String name;
public MyExecute(String name) {
this.name = name;
}
public void run() {
Thread.currentThread().setName(this.name);
System.out.println(Thread.currentThread().getName());
}
}
public class Server {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
i++;
Thread t = new Thread(new MyExecute("name" + i));
t.start();
}
}
}
class MyExecute implements Runnable {
private String name;
public MyExecute(String name) {
this.name = name;
}
public void run() {
Thread.currentThread().setName(this.name);
System.out.println(Thread.currentThread().getName());
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询