2013-04-22 27 views
0

一个线程继续读取从BufferedReader收到的字节。数据来自SerialPort如何处理2个线程使用的变量?

在主线程中,点击时有一个JMenuItem,串口关闭,BufferedReader应该停止接收消息。

的问题是:

如果我试图关闭的同时,在阅读邮件,应用程序将卡和串行端口不会被关闭,直到端口停止发送消息。

所以基本上,我应该在关闭串口前关闭读卡器。如果我这样做,有时会得到一个空指针异常,因为我正在读取缓冲读取器时关闭它。

我该如何解决这个问题?

+1

你关心'BufferedReader'在关闭JMenuItem时读的是什么吗? – supersam654 2013-04-22 20:58:34

+0

@ supersam654是的 – 2013-04-23 13:42:47

回答

1

这听起来像你可以在你的读者类stop方法解决这个问题(从菜单项中的click事件调用)

private boolean isStopped = false; 

public void stop() { 
    isStopped = true; 
} 

while(bufferedReader.isReady()) { 
    bufferedReader.read(); 
    if(isStopped) { 
     bufferedReader.close(); 
    } 
} 

这样可以确保你不叫close直到所有read电话已完成。

+0

嗯,这工作。谢谢,非常简单的实现。 – 2013-04-23 13:42:25

0

最简单的事情就是创建一个SynchronizedReader类来包装您的BufferedReader。但没有更多的上下文,我不能保证这将工作,特别是如果你有调用代码,使多个相互依赖的调用Reader(你需要确保所有的调用是在一个synchronized(reader)块)。

import java.io.IOException; 
import java.io.Reader; 
import java.nio.CharBuffer; 

public class SynchronizedReader extends Reader { 

    private Reader reader; 

    public SynchronizedReader(Reader reader) { 
     super(); 
     this.reader = reader; 
    } 

    @Override 
    public synchronized int read(char[] cbuf, int off, int len) throws IOException { 
     return reader.read(cbuf, off, len); 
    } 

    @Override 
    public synchronized void close() throws IOException { 
     reader.close(); 
    } 

    @Override 
    public synchronized int hashCode() { 
     return reader.hashCode(); 
    } 

    @Override 
    public synchronized int read(CharBuffer target) throws IOException { 
     return reader.read(target); 
    } 

    @Override 
    public synchronized int read() throws IOException { 
     return reader.read(); 
    } 

    @Override 
    public synchronized int read(char[] cbuf) throws IOException { 
     return reader.read(cbuf); 
    } 

    @Override 
    public synchronized boolean equals(Object obj) { 
     return reader.equals(obj); 
    } 

    @Override 
    public synchronized long skip(long n) throws IOException { 
     return reader.skip(n); 
    } 

    @Override 
    public synchronized boolean ready() throws IOException { 
     return reader.ready(); 
    } 

    @Override 
    public synchronized boolean markSupported() { 
     return reader.markSupported(); 
    } 

    @Override 
    public synchronized void mark(int readAheadLimit) throws IOException { 
     reader.mark(readAheadLimit); 
    } 

    @Override 
    public synchronized void reset() throws IOException { 
     reader.reset(); 
    } 

    @Override 
    public synchronized String toString() { 
     return reader.toString(); 
    } 

}