dghtr
dghtr

Reputation: 581

Regarding Daemon thread

I was doing a sort of research in which I want to make a user thread as a daemon thread ,Thread.setDaemon(true) makes a Thread daemon, but as we knowDaemon Threads are suitable for doing background job, so I want to link my this thread to any background daemon thread so that my daemon thread can provide some services to that thread and it should end when that daemon threads end, although I have created the daemon thread but please advise how I would provide the services through my daemon thread to any existing daemon thread and then it should end up at last, please advise.

     Thread daemonThread = new Thread(new Runnable(){
            @Override
           public void run(){
               try{
               while(true){
                   System.out.println("Daemon thread is running");
               }

               }catch(Exception e){

               }finally{
                   System.out.println("Daemon Thread exiting"); //never called
               }
           }
       }, "Daemon-Thread");

       daemonThread.setDaemon(true); //making this thread daemon
       daemonThread.start();


}

Upvotes: 1

Views: 193

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533880

I don't know exactly what you mean but I would change

while(true){

to

while(!Thread.currentThread.isInterrupted()){

This will allow your thread to stop when interrupted.

I would also consider using an ExecutorService as this makes it easier to pass work to another thread and shut it down when you are finished.

ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r, "worker");
        t.setDaemon(true);
        return t;
    }
});

service.submit(new Runnable() { /* task for this thread to perform */ });

service.shutdown(); // to stop it.

Upvotes: 2

Related Questions