简体   繁体   English

如何获得java中的主线程?

[英]How to get the main thread in java?

So I have a long running process that I want to encapsulate as a Runnable and dispatch it in a thread.所以我有一个长时间运行的进程,我想将其封装为 Runnable 并将其分派到一个线程中。 To be more specific, I have a POST web service that creates a file in the file system but the creation of the file can take a very long time.更具体地说,我有一个 POST web 服务,它在文件系统中创建一个文件,但创建文件可能需要很长时间。

In the resource method of my web service, I want to be able to dispatch a thread to do the file creation and return the status 200. I don't think I can just do Thread.join because this would mean that the current thread would have to wait for the file creation thread to finish.在我的 web 服务的资源方法中,我希望能够调度一个线程来创建文件并返回状态 200。我认为我不能只做 Thread.join 因为这意味着当前线程会必须等待文件创建线程完成。 Instead, I want to join the file creation thread to the main thread.相反,我想将文件创建线程加入主线程。 Question is, how do I get the main thread in java?问题是,我如何获得 java 中的主线程?

I am not sure whether I get you right.我不确定我是否正确。 Here is what I understood:这是我的理解:

You want to preform a possibly long running operation (file creation) you do not want you service method to block while that task is exectued you want the task executed in a thread that exists outside the boundary/lifetime of the single request.您想要执行一个可能长时间运行的操作(文件创建),您不希望您的服务方法在执行该任务时阻塞您希望该任务在单个请求的边界/生命周期之外存在的线程中执行。

Am I right so far?到目前为止我是对的吗?

If sou really recommend you look into the newer concepts in java.util.concurrent.如果真的建议您查看 java.util.concurrent 中的更新概念。 The concepts described there should give you enogh information tackkle this那里描述的概念应该给你足够的信息来解决这个问题

Basic credo: Don't think in threads, think in tasks.基本信条:不要在线程中思考,在任务中思考。

General Book recommendation: Java Concurrency in Practice by Brian Goetz通用书籍推荐:Java Concurrency in Practice by Brian Goetz

You will need to process the request asynchronously.您将需要异步处理请求。 A separate thread will be created for doing the heavy work and the request receiving thread will be free to process other requests.将创建一个单独的线程来完成繁重的工作,并且请求接收线程将可以自由处理其他请求。 Please checkout following articles.请查看以下文章。

When you spawn the file-creation thread, you need to pass it some kind of reference to the parent thread, so it can communicate back (ie you provide something to enable a callback).当您产生文件创建线程时,您需要将某种引用传递给父线程,以便它可以返回通信(即您提供一些东西来启用回调)。

This could be the actual Thread object (obtained using Thread.currentThread, as someone said in a comment) or some other object that you use to signal when the file-creation thread is done.这可能是实际的线程 object (使用 Thread.currentThread 获得,正如有人在评论中所说)或其他一些 object 用于在文件创建线程完成时发出信号。

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

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