SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Oct 2008
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Start a thread from a servlet

    Hi ppl,
    I tried lot of methods to run my thread continuously but it affects performance of my application
    i want to start the thread wen application starts and want to end it wen appl ends. it can be done in servlets.im new to it.can anyone help me with it

    THANKS IN ADVANCE

  2. #2
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I want to start the thread when application starts and want to end it when application ends
    Code:
    public static void main(String[] args) {
            Thread t = new Thread(new Runnable() {
    
                public void run() {
                    for (;;) {
                        System.out.println("Hello");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
    
            });
            t.setDaemon(true); // this makes the Thread die when your application exits!
            t.start();
    }
    Try change the daemon value to false, you'll see the difference.

    You can start the thread from any Java class (this means Servlets too).

    Some related info...
    http://www.google.com/search?q=java+thread+examples
    http://java.sun.com/j2se/1.4.2/docs/...ng/Thread.html

  3. #3
    SiteP0int Weazle hooknc's Avatar
    Join Date
    Dec 2004
    Location
    Socialist Republic of Boulder
    Posts
    937
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As an on the side note...

    To start a thread or any type of work that needs to start at the beginning of a web server... It would be better to use a ServletContextListener instead of a Servlet. The servlet should work, but listening to events from the ServletContext would be better.
    baby steps... baby steps...


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •