Reputation: 1
For the below code,
static class SleeperThread extends Thread {
public void run() {
int c;
try {
c = System.in.read();
}
...
}
}
As mentioned in this bug, If a thread is blocked on IO(System.in.read();
), then, Can't the interrupt flag be set on that thread, by another thread?
Upvotes: 1
Views: 174
Reputation: 4430
Since System.in
doesn't react on Thread interrupts you have to implement something like it yourself.
To do that you can use the method available()
of the System.in
(of InputStream
).
It might look somewhat like this:
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");
}
}
}
Upvotes: 1