简体   繁体   English

在无状态代理中同时运行两个线程并确保它们之间的通信

[英]running two threads simultaneously inside a stateless agent and guaranting communication between them

I am developing a stateless Agent in Java that takes informations from one Server and transfer it to another client. 我正在用Java开发无状态代理,该代理从一台服务器获取信息并将其传输到另一台客户端。 It means that the agent is located between a client and a server. 这意味着代理位于客户端和服务器之间。 So I am thinking to run two threads simultaneously on the agent: one thread (thread1) runs a serverSocket and get request from client while another threads (thread2)is runnning and makes communication with the server. 因此,我正在考虑在代理上同时运行两个线程:一个线程(线程1)运行serverSocket并从客户端获取请求,而另一个线程(线程2)正在运行并与服务器进行通信。 The problem consists in synchronizing between the two threads. 问题在于两个线程之间的同步。 I am thinking in making thread 1 asking whole the time thread 2 about a new Information. 我正在考虑使线程1整个时间都在线程2中询问新信息。 If thread 2 has nothing new, he will not answer it. 如果线程2没有新内容,他将不会回答。 What is the best way to synchronize between them. 在它们之间进行同步的最佳方法是什么。 Should I use a global variable (a flag) to synchronize between them? 我应该使用全局变量(标志)在它们之间进行同步吗? Can I save Information when I have a stateless agent? 拥有无状态代理后,我可以保存信息吗?

I think you should modify your app into async model . 我认为您应该将应用程序修改为异步模型

Your app needs: 您的应用程序需要:
- an entry point to accept incoming connections -> a good example is an async servlet (or one dedicated thread). -接受传入连接的入口点->一个很好的例子是异步servlet(或一个专用线程)。
- a ThreadPoolExecutor that provides fixed numbers of workers and a blocking queue (use this constructor). -ThreadPoolExecutor,提供固定数量的工作程序和阻塞队列(使用构造函数)。

The workflow: 工作流程:

  1. Accept incomming request. 接受进来的请求。
  2. Wrapp incoming request into (Runnable) task. 将传入请求打包到(Runnable)任务中。
  3. Put task into blocking queue. 将任务放入阻塞队列。
  4. If ThreadPoolExecutor has a free worker starts processing the task 如果ThreadPoolExecutor有空闲工作者开始处理任务

An advantage of such a model is that you are able to handle one request using one thread . 这种模型的优点是您可以使用一个线程处理一个请求 So there is no need to manually synchronize anything. 因此,无需手动同步任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM