操作系统:会有个多个进程
一个进程多个线程
线程都有各自的计算器、堆栈和局部变量等属性,并且都能
够访问共享的内存变量。处理器(cpu时间片)在这些线程
上高速切换,让使用者感觉到这些线程在同时执行。
现在操作系统基本是采用时分的形式调度运行的线程,操作系统会分出一个一个时间片。线程会分到若干的时间片。
java 天生适合多线程。
priority 优先级
默认5 优先级越高分配的时间片数量越多
线程状态:
初始 运行 阻塞 等待 超时等待 终止
interrupt()中断和其他配合
interrupted 标识位
isAlive 标识位
wait 等待释放锁 sleep 不释放锁。
join本质 源码
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0); //join(0)等同于wait(0),即wait无限时间直到被notify
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}