我有两个Java文件:
Check.java
import java.util.concurrent.Semaphore;
class Check
{
public static void main(String[] args)
{
Semaphore s = new Semaphore(1);
MyThread t1 = new MyThread("t1",s);
MyThread t2 = new MyThread("t2",s);
t1.start();
t2.start();
t2.interrupt();
}
}
MyThread.java
import java.util.concurrent.Semaphore;
class MyThread extends Thread
{
Semaphore s;
MyThread(String name, Semaphore s)
{
super(name);
this.s=s;
}
public void run()
{
try
{
s.acquireUninterruptibly();
for(int i=0; i<5; i++)
{
Thread.sleep(500);
System.out.println(Thread.currentThread().getName()+"-"+i);
}
s.release();
}
catch(InterruptedException e){}
}
}
如果我注释掉语句“ t2.interrupt()”,则两个线程都可以正常执行。但是,如果我不评论该语句,则线程t2根本不会执行。根据我对acquireUninterruptible()方法的理解,线程t2即使在获得中断后也应继续等待许可。那么为什么线程t2在收到中断后停止工作?
方法acquireUninterruptibly
仅表示从Semaphore
获得许可,而不中断当前持有许可的线程。执行s.acquireUninterruptibly()
的线程仍可中断。这就是线程t2仍然中断的原因。不中断不会阻止执行该方法的线程中断。
我认为文档相当混乱。从Semaphore的文档中获取:
从此信号量获取许可,阻塞直到可用,否则线程被中断。
什么线程是“线程”尚不清楚(或者可能在开始时隐藏了100行描述。)。尝试查看Semaphore类中其他方法的描述,我发现文档使用“当前线程”引用执行该方法的线程,而“该线程”引用其他线程。