Locksupport類可以實現線程的使用(yong)和喚醒
park(): 阻塞當前線程
unpark(thread): 喚醒(xing)指定線(xian)程(cheng)
使用舉例:a,b,c三個線(xian)(xian)程同(tong)時(shi)啟動(dong),a線(xian)(xian)程打印a,b線(xian)(xian)程打印b,c線(xian)(xian)程打印c,如何用Java代碼實現(xian)按順序打印abc,循環(huan)十次。
public static void main(String[] args) {
Thread a,b,c;
a = new Thread(() -> {
LockSupport.park();
for(int i=0;i<10;i++){
System.out.print(Thread.currentThread().getName());
LockSupport.park();
}
},"a");
b = new Thread(() -> {
LockSupport.park();
for(int i=0;i<10;i++){
System.out.print(Thread.currentThread().getName());
LockSupport.park();
}
},"b");
c = new Thread(() -> {
LockSupport.park();
for(int i=0;i<10;i++){
System.out.print(Thread.currentThread().getName());
LockSupport.park();
}
},"c");
a.start();
b.start();
c.start();
int count = 1;
for(;;){
if(!a.isAlive() && !b.isAlive() && !c.isAlive()){
break;
}
if(count%3 == 1){
LockSupport.unpark(a);
}
if(count%3 == 2){
LockSupport.unpark(b);
}
if(count%3 == 0){
LockSupport.unpark(c);
}
try {
// 主線程休眠10毫秒是為了把cpu的使用權讓給 a/b/c 線程
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}