Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在线程上设置中断标志_Java_Multithreading - Fatal编程技术网

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一样)。总有另一种方法来实现你的目标<代码>线程。睡眠
不会“自行”检查。它的实现是为了明确地检查中断。