LockSupport普通例子:
public class LockSupportPark {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new Runnable() {
public void run() {
//阻塞当前线程
LockSupport.park();
System.out.println("thread end");
}
});
t.start();
System.out.println("sleep start");
Thread.sleep(2000);
System.out.println("sleep end");
//唤醒线程,让其继续执行下去
LockSupport.unpark(t);
}
}
输出: sleep start sleep end thread end 用LockSupport实现锁例子:
//锁状态,0代表未加锁,1代表已加锁
volitile int status = 0;
//将获取锁失败的线程放到该队列中,等锁释放后pop出队列头部第一个线程,并唤醒它让其重新竞争锁
Queue queue = new Queue();
public boolean lock(){
//成功地将0改成1则代表获得锁成功
while(!completeAndSet(status,0,1)){
//进入while循环代表获取锁失败
//将失败线程放进队列中
queue.add(currentThread);
//挂起当前线程,线程会在这里阻塞
LockSupport.park();//底层用的是UNSAFE类的方法
}
//跳出while循环代表获取锁成功,然后返回true
return true;
}
public void unLock(){
//将锁状态置为0
status = 0;
//将队列中第一个线程来拿出来
Thread t = queue.pop();
if (t != null) {
//唤醒该线程让它继续执行
LockSupport.unpark(t);//底层用的是UNSAFE类的方法
}
}