在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
提交
取消