Java 在线程上设置中断标志
对于下面的代码Java 在线程上设置中断标志,java,multithreading,Java,Multithreading,对于下面的代码 static class SleeperThread extends Thread { public void run() { int c; try { c = System.in.read(); } ... } } 如本文所述,如果一个线程在IO上被阻塞(System.in.read();),那么,另一个线程不能在该线程上设置中断标志吗?,因为System.in不会对线程中断做出反应,您必须自己实现类似的功能 要做到这
static class SleeperThread extends Thread {
public void run() {
int c;
try {
c = System.in.read();
}
...
}
}
如本文所述,如果一个线程在IO上被阻塞(
System.in.read();
),那么,另一个线程不能在该线程上设置中断标志吗?,因为System.in
不会对线程中断做出反应,您必须自己实现类似的功能
要做到这一点,您可以使用系统的available()
方法
它可能看起来有点像这样:
class ReadWithInterrupt extends Thread{
private byte[] result = null;
public byte[] getResult(){
return result;
}
@Override
public void run(){
try{
while(true){
if (this.isInterrupted()){
System.out.println("An interrupt occurred");
break;
}
int available = System.in.available();
if (available>0){
result = new byte[available];
System.in.read(result, 0, available);
break;
}
else
Thread.sleep(500);
}
}
catch (IOException e){
e.printStackTrace();
}
catch (InterruptedException e){
System.out.println("An interrupt occurred");
}
}
}
是的,它可以。问题是,read()
不检查线程中断。@因此,中断标志被设置,但由于java线程中断本质上是同步的,不像硬件中断,我们需要等待read()
完成。Java线程中断本质上是协作的:线程必须显式地检查中断,而不仅仅是“发生”。@overexchange不使用中断。。。有太多的操作不会对中断做出反应!(就像System.in一样)。总有另一种方法来实现你的目标<代码>线程。睡眠
不会“自行”检查。它的实现是为了明确地检查中断。