简体   繁体   中英

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. 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.

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. Instead, I want to join the file creation thread to the main thread. Question is, how do I get the main thread in 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. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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