java网络多线程

发布于 2024-12-13 05:48:39 字数 476 浏览 1 评论 0原文

我正在尝试构建一个可以同时接受来自多个客户端的文件的服务器。

但它是按顺序提交文件,我不明白为什么......

任何人都可以帮忙吗?谢谢你,

我发布了两个线程的片段。每次我接受连接时,我都会实例化提交类并执行它们。

This is main thread that accepts connections
int poolSize = 1; 
    int maxPoolSize = 3;
    long keepAliveTime = 10;
    ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(5);
    threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue);

I am trying to build a server that can concurrently accept files from multiple clients.

But it is submitting files sequentially and I don't understand why....

Can anyone help? Thank you

I post my snippet of two threads. everytime I accept connection, I instantiate Submission class and execute them.

This is main thread that accepts connections
int poolSize = 1; 
    int maxPoolSize = 3;
    long keepAliveTime = 10;
    ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(5);
    threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

权谋诡计 2024-12-20 05:48:39

Submission 类的 run() 方法中的锁导致该部分代码按顺序运行。该锁是通过构造函数传入的,因此它在所有孩子之间共享,因此他们都在运行 stats.logSubmission 之前调用 lock.lock() 。这意味着一次只有一个线程会调用 logSubmission。

作为实现并发的快速方法;尝试删除锁定,而不是立即写入文件,而是尝试将日志记录存储在 ConcurrentLinkedQueue。然后,您可以在稍后执行时或在某些条件(大小、时间等)下将它们刷新到磁盘。该队列是无锁、快速且线程安全的。

The lock in the run() method of Submission class is causing that portion of your code to run sequentially. That lock is passed in via the constructor so it's shared between all your children, so they all call lock.lock() before running the stats.logSubmission. Which means only one thread at a time is going to call logSubmission.

As a quick way to get this concurrent; try removing the lock and instead of writing to files right away, try storing the logs records in a ConcurrentLinkedQueue. You can then flush them to disk at some later point in execution or on some condition (size, time,..). That queue is a lock-free, fast and thread safe.

酷到爆炸 2024-12-20 05:48:39

本质上,您需要将 .accept() 新连接的线程与处理这些请求的线程分开。

每次在服务器套接字上调用 .accept() 时,都会生成一个新线程来处理该请求,并将来自 .accept() 的套接字连接传递到该线程中方法。

Essentially, you need to separate the thread where you .accept() new connections, and where you handle those requests.

Every time you call .accept() on the server socket, spawn a new thread to handle that request, and pass into that thread the socket connection from the .accept() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文