创建一个指定名字的线程
若不指定名字,JVM会给定一个名字;
private static class MyRunnable implements Runnable{
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Thread thread1 = new Thread(myRunnable, "我是指定名字的线程");
thread1.start();;
}
使用JConsole工具查看线程名称
属性
public static void main(String[] args) {
Thread currentThread = Thread.currentThread();
System.out.println(currentThread.getName());
System.out.println(currentThread.getId());
System.out.println(currentThread.getState());
System.out.println(currentThread.getPriority());
System.out.println(currentThread.isDaemon());
System.out.println(currentThread.isAlive());
System.out.println(currentThread.isInterrupted());
System.out.println(currentThread.getThreadGroup());
}
//结果
main//线程名称
1//线程ID
RUNNABLE//线程状态
5//线程优先级,越高越好
false//是否是精灵(守卫)线程
true//是否活着
false//是否有其他线程要改线程die
java.lang.ThreadGroup[name=main,maxpri=10]//线程组
JAM会将创建的线程分别放入线程组中;