Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.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 object.wait是否可以中断?_Java_Multithreading - Fatal编程技术网

Java object.wait是否可以中断?

Java object.wait是否可以中断?,java,multithreading,Java,Multithreading,在Java文档中,它说中断函数可以中断对象。wait。但在我的测试中,在windows中是的,它可以被中断,但在Linux中是错误的,它不能被中断 原因似乎是Glibc 2.1.3中的pthread_cond_wait无法再被系统信号中断 我的理解正确吗 public static void main(String[] args) { Thread t = new Thread() { public void run() {

在Java文档中,它说中断函数可以中断
对象。wait
。但在我的测试中,在windows中是的,它可以被中断,但在Linux中是错误的,它不能被中断

原因似乎是Glibc 2.1.3中的pthread_cond_wait无法再被系统信号中断

我的理解正确吗

public static void main(String[] args)
{

    Thread t = new Thread()
    {
        public void run()
        {
            Object obj = new Object();
            synchronized(obj) {
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    System.out.println("interrupted");
                    e.printStackTrace();
                }
            }
        }
    };

    t.start();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    t.interrupt();
            System.out.println("interrupt is called");
            try {
        Thread.sleep(100000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

JavaAPI说一个等待的线程可以被另一个线程中断。JavaAPI总是正确的。所有JVM实现都必须遵守其说明。

例如,以下java代码:

mdInputStream = new BufferedInputStream( new FileInputStream( new File( MD_CONFIG_FILE )));
SessionSettings mdSettings = new SessionSettings(mdInputStream);
mdInputStream.close();

LogFactory mdScreenLogFactory = new ScreenLogFactory(true, true, true, true);
LogFactory mdFilelogFactory = new FileLogFactory(mdSettings);

MessageFactory messageFactory = new DefaultMessageFactory();

mdInitiator = new SocketInitiator(mdApplication, mdMessageStoreFactory, mdSettings, mdFilelogFactory, mdScreenLogFactory, messageFactory);
mdInitiator.start();

您应该始终正确地尊重中断,并将其理解为尽快优雅地终止的请求。系统是否真的可以执行中断是无关紧要的,因为您的代码可以在许多不同的机器和操作系统上运行


在您的代码中,请在末尾添加一个
t.join()
,并检查它在Linux上是否仍然不可中断。因为可能是程序在线程被授予实际处理中断的时间之前终止得太快。

听起来很奇怪。请出示您的代码。代码已经发布。很抱歉,在我的测试中,我有一些代码,比如在调用中断函数后,长时间睡眠来监控中断。但这条线索仍然没有中断。然后我认为中断方法无法在某些阻塞调用(如object.wait())中正常工作。这有两个测试:一个是程序终止,另一个是对您使用的JVM的测试。因为这种使用t.join()的构造经常发生,如果它不可中断,许多程序将无法终止。