在main方法中,有4個LockSupport.unpark方法,當t1線程運行時應該Lock.park()不應該堵塞代碼,但是實際是堵塞的為什么,為什么main方法中注釋中的方法就可以輸出11111,park方法沒有阻塞當前進程。
public class LockSupportDemo {
public static Object u = new Object();
static ChangeObjectThread t1 = new ChangeObjectThread("t1");
public static class ChangeObjectThread extends Thread{
public ChangeObjectThread(String name)
{
super.setName(name);
}
@Override
public void run() {
synchronized (u)
{
LockSupport.park(Thread.currentThread());
System.out.println("in "+ getName());
if(Thread.interrupted())
{
System.out.println(getName()+" interrupted");
}
}
System.out.println(getName() +"isOver");
}
}
public static void main(String[] args) throws InterruptedException {
LockSupport.unpark(t1);
LockSupport.unpark(t1);
LockSupport.unpark(t1);
LockSupport.unpark(t1);
LockSupport.unpark(t1);
t1.start();
/**
*LockSupport.unpark(Thread.cuurentThread);
*LockSupport.unpark(Thread.cuurentThread);
*Lock.park();
*System.out.println("11111");
*
*/
}
}
2 回答

牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
LockSupport#unPark()
方法注釋有說明,如下:
Makes available the permit for the given thread, if it was not already available. If the thread was blocked on park then it will unblock. Otherwise, its next call to park is guaranteed not to block. This operation is not guaranteed to have any effect at all if the given thread has not been started.
加粗斜體部分已經說明,不會保證方法功能,如果線程未啟動之前操作。
所以先要t1.start()
添加回答
舉報
0/150
提交
取消