Can i spawn a thread from a servlet?

前端 未结 2 726
暗喜
暗喜 2021-01-05 10:09

I would like to ask a basic question before i get on to my main question .

Lets say i am running a simple Java program, which spawns a thread in the main function. W

相关标签:
2条回答
  • 2021-01-05 10:41

    When you want your application to exit even though you still have running threads, you have to mark your thread as a daemon thread:

    Thread t = new Thread(myRunnable);
    t.setDaemon(true),
    t.start();
    

    This is especially important when you do that in an application server, otherwise the server cannot be shut down!

    If you do that repeatedly you might want to consider a ThreadPool to make this more efficient

    0 讨论(0)
  • 2021-01-05 11:03
    • There is such thing as parent and child threads, but you don't have a lot of control on that. For example there's InheritableThreadLocal, where you can store variables for a thread hierarchy.

    • you can spawn a new thread from a servlet. Prefer Java 5 executors framework

    • if using servlet 3.0, take a look at its asynchronous processing capabilities.

    0 讨论(0)
提交回复
热议问题