1.CPU的上下文切换,cpu的使用权就是一段时间片,上下文切换消耗资源的原因是当线程1执行中段,将指令指针写回到主存,然后切换到新的线程2,执行完后,然后读取之前中断的那个时候的状态,再去执行。
进程是在pcb进程控制区块(主存),
1.pc,程序计数器,存的是程序指令的地址,指令在主存里面
2,Registers(几十个),寄存器,将主存的指令读进来
3.ALU,算术逻辑单元,计算完结果,回写到主存中
2.jvm是运行再操作系统上面的,用户态空间,经过操作系统叫CPU创建新的时间片用来处理jvm的新线程,当线程1释放cpu使用权的时候,中间变量回写到寄存器,
3.synchronized,实现了Lock接口
4,ReentrantLock,,,内部变量Sync继承自AbstractQueuedSynchronizer,通过debug可以看到,,有head,tail,state(当前加锁的次数),和exclusiveOwnerThread(当前占有锁的线程)四个变量,基于CLH队列实现(双向链表,原来的自旋机制改为了阻塞机制)
CLH出队,就是head之后得一个Node 1,先将1的Thread=null线程置空,将head移除,将1得prv指向null
条件队列=
尝试获得锁的时候,调用方法
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}