1 线程各属性纵览
2 线程Id
/**
* ID从1开始,JVM运行起来后,我们自己创建的线程的ID早已不是2
*/
public class Id {
public static void main(String[] args) {
Thread thread = new Thread();
//java.lang.Thread.nextThreadID
System.out.println("主线程的ID:"+Thread.currentThread().getId());
System.out.println("子线程的ID:"+thread.getId());
}
}
3 线程名字
默认线程名字源码分析
//java.lang.Thread#Thread()
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
修改线程的名字(代码演示、源码分析)
线程启动起来后依然可以设置名字,但是native层的名字必须启动之前设置
//java.lang.Thread#setName
public final synchronized void setName(String name) {
checkAccess();
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name;
//C++层给线程设置名字
if (threadStatus != 0) {
setNativeName(name);
}
}
private native void setNativeName(String name);
/* Java thread status for tools,
* initialized to indicate thread 'not yet started'
*/
private volatile int threadStatus = 0;
4 守护线程
作用:给用户线程提供服务
特性
- 线程类型默认继承自父线程
- 通常情况下由JVM启动,用户创建线程后也可以设置该线程为守护线程(main为非守护线程)
不影响JVM退出
1. 守护线程和普通线程的区别
- 整体无区别
- 唯一区别在于JVM的离开
2. 我们是否需要给线程设置为守护线程?
不应该:如果我的线程是读写文件,我把它设置为守护线程后,当没有其他线程运行的时候,我这个线程是会被JVM给强行停止的
5 线程优先级
10个级别,默认5
程序设计不应依赖于优先级
- 不同操作系统不一样 (Windows只有7个)
优先级会被操作系统改变
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;