1.当有很多线程在执行的时候,我们怎么去区分这些线程呢?
此时需要使用Thread的常用方法:getName(),setName(),currentThread()等
package com.my;
//定义个一个线程,进程Thread
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(Thread.currentThread().getName()+"线程");
}
}
}
package com.my;
public class Test {
public static void main(String[] args) {
//new一个线程 使用setName进行起名字
//
Thread te1 = new MyThread();
te1.setName("一号");
te1.start();
Thread te2 = new MyThread();
te2.setName("二号");
te2.start();
//使用Thread.currentThread().getName()获取线程名字
for (int i = 0; i < 50; i++) {
System.out.println(Thread.currentThread().getName()+"线程");
}
}
}
使用构造方法给线程起名字:
package com.my;
//定义个一个线程,进程Thread
public class MyThread extends Thread {
//使用构造方法进行给线程取名字
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(Thread.currentThread().getName()+"线程");
}
}
}
package com.my;
public class Test {
public static void main(String[] args) {
//使用构造器给线程起名字
Thread te1 = new MyThread("一号");
te1.start();
Thread te2 = new MyThread("二号");
te2.start();
//使用Thread.currentThread().getName()获取线程名字
for (int i = 0; i < 50; i++) {
System.out.println(Thread.currentThread().getName()+"线程");
}
}
}
Runnable怎么给线程起名字?
直接使用Thread有参构造器起名字。