1.线程各属性纵览
属性名称 | 用途 |
---|---|
编号(ID) | 每个线程有自己的ID,用于标识不同的线程 |
名称(Name) | 作用让用户或程序员在开发、调试或运行过程中,更容易区分每个不同的线程、定位问题等。 |
是否是守护线程(isDaemon) | true代表该线程是【守护线程】,false代表线程是非守护线程,也就是【用户线程】。 |
优先级(Priority) | 优先级这个属性的目的是告诉线程调度器,用户希望哪些线程相对多运行、哪些少运行。 |
2.线程Id
/**
* 描述: ID从1开始,JVM运行起来后,我们自己创建的线程的ID早已不是2.
*/
public class Id {
public static void main(String[] args) {
Thread thread = new Thread();
System.out.println("主线程的ID" + Thread.currentThread().getId());
System.out.println("子线程的ID" + thread.getId());
}
}
主线程的ID1
子线程的ID12
源码:
- Thread.currentThread().getId()
private static synchronized long nextThreadID() {
return ++threadSeqNumber;
}
3 线程名字
3.1.默认线程名字源码分析
- new Thread()
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
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;
public class ThreadSetName {
public static void main(String[] args) {
Thread thread = new Thread();
thread.start();
thread.setName("mythread");
System.out.println(thread.getName());
}
}
4 守护线程
作用:给用户线程提供服务
特性
- 线程类型默认继承自父线程
- 通常情况下由JVM启动,用户创建线程后也可以设置该线程为守护线程(main为非守护线程)
- 不影响JVM退出
守护线程和普通线程的区别
- 整体无区别
- 唯一区别在于JVM的离开(守护线程不会影响JVM的退出)
我们是否需要给线程设置为守护线程?
不应该:一旦把我们自己的线程设置为守护线程是非常危险的,比如说线程正在访问文件,发现你只剩下守护线程了,JVM就关闭退出了,这个线程就会被JVM强行终止,导致数据的不一致。
5 线程优先级
10个级别,默认5
程序设计不应依赖于优先级
- 不同操作系统不一样 (Windows只有7个 会进行 线程优先级映射 如Java 1、2级对应windows最低级)
- 优先级会被操作系统改变
/**
* 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;
6 线程各属性总结
属性名称 | 用途 | 注意事项 |
---|---|---|
编号(ID) | 标识不同的线程 | 被后续创建的线程使用;唯一性;不允许被修改 |
名称(Name) | 定位问题 | 清晰有意义的名字;默认的名称 |
是否是守护线程(isDaemon) | 守护线程、用户线程 | 二选一;继承父线程;setDaemon |
优先级(Priority) | 相对多运行 | 默认和父线程的优先级相等,共有10个等级,默认值是5;不应依赖 |
网友评论