首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何消除Rox NIO教程中的竞争条件

如何消除Rox NIO教程中的竞争条件
EN

Stack Overflow用户
提问于 2012-01-11 01:20:21
回答 1查看 430关注 0票数 1

我一直在使用this教程来实现一个使用socket IO的简单文件传输客户端/服务器。我更改了响应处理程序,将多个读取作为一个文件的一部分接受,因为我将处理大文件,可能高达500MB。本教程没有考虑到大型服务器响应,所以我有点挣扎,并且我创建了一个竞争条件。

下面是响应处理程序代码:

代码语言:javascript
复制
public class RspHandler {

private byte[] rsp = null;
public synchronized boolean handleResponse(byte[] rsp) {
    this.rsp = rsp;
    this.notify();
    return true;
}

public synchronized void waitForResponse() {
    while(this.rsp == null) {
        try {
            this.wait();
        } catch (InterruptedException e) {
        }
    }
    System.out.println("Received Response : " + new String(this.rsp));
}

public synchronized void waitForFile(String filename) throws IOException {
    String filepath = "C:\\a\\received\\" + filename;
    FileOutputStream fos = new FileOutputStream(filepath);
    while(waitForFileChunk(fos) != -1){}
    fos.close();
}

private synchronized int waitForFileChunk(FileOutputStream fos) throws IOException
{
    while(this.rsp == null) {
        try {
            this.wait();
        } catch (InterruptedException e) {
        }
    }
    fos.write(this.rsp);
    int length = this.rsp.length;
    this.rsp = null;
    if(length < NioClient.READ_SIZE)//Probably a bad way to find the end of the file
    {
        return -1;
    }
    else
    {
        return length;
    }

}
}

程序的主线程在主线程上创建一个RspHandler,并将其传递给在单独线程上创建的客户端。主线程告诉客户端请求一个文件,然后告诉RspHandler侦听响应。当客户端从服务器读取数据时(它现在读取的块大小约为1KB ),它调用handleResponse(byte[] rsp)方法,填充rsp字节数组。

从本质上讲,我不会将接收到的数据以最快的速度写入文件。我对线程还是个新手,所以我不知道该怎么做才能摆脱这种竞争状况。有什么提示吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-01-11 01:44:59

这是典型的消费者/生产者。处理此问题的最直接/最简单的方法是使用BlockingQueue。生产者调用put(),消费者调用take()

注意,使用BlockingQueue通常会导致“如何完成”的问题。要做到这一点,最好的方法是使用“毒丸”方法,生产者在队列上粘贴一个“特殊”值,该值向消费者发出没有更多数据的信号。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8807551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档