简体   繁体   中英

Is posible to know if a certain Thread is alive?

for my purposes of html parsing, I have implemented a PRODUCER/CONSUMER PATTERN. MY problem is the way in wich I can stop the consumer after that a producer have finished the task and a condivised buffer is emtpy . EXAMPLE:

I have one PRODUCER and 5 CONSUMER. The producer stop to work because have complished its tasks. So the Consumer how can know that the producer has finished its work?? I have try to implement:

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.LinkedBlockingQueue;

public class MainTest {

  public static void main(String[] args) {

    BlockingQueue queue = new LinkedBlockingQueue<String>( );



    Producer p = new Producer(queue,"0");
   // FOR ALL CONSUMER I PASS THE REFERENCE TO THE UNIQUE PRODUCER !!!
    Consumer c1=new Consumer(queue,"1",p);
    Consumer c2=new Consumer(queue,"2",p);
   Consumer c3=new Consumer(queue,"3",p);
   Consumer c4=new Consumer(queue,"4",p);
    Consumer c5=new Consumer(queue,"5",p);

    p.start();

     c1.start();c2.start();c3.start();c4.start();c5.start();


  }
}
THE PRODUCER:
class Producer extends Thread{

      BlockingQueue<String> queue;

      public Producer(BlockingQueue<String> queue, String s) {
          super ("THREAD"+s);
        this.queue = queue;
      }

      @SuppressWarnings("deprecation")
    public void run(){
        int messagecode = 1;


 boolean flagLavora= true;
        //ciclo infinito
        while(flagLavora ){
          try {
              System.out.println("-------------------------------------------------------------");


              System.out.println(" : IS ALIVE "+Thread.currentThread().isAlive()+" ");
              System.out.println(" IS INTERRUPTED "+Thread.currentThread().isInterrupted()+" ");

                  System.out.println( this.getName()+">>"+"PRODUTT  Thread");

                System.out.println("Producing "+(++messagecode));

                     queue.put("MESSAGE@"+messagecode);

                       System.out.println(messagecode+" in queue");
                System.out.println("SIZE QUEUE:"+queue.size());


                if (messagecode %9==0) 
                 { 
                    System.out.println(  "STATE PRODUTT "+ Thread.currentThread().getState());
                    System.out.println( this.getName()+">>PRODUTT CLOSE");
                    System.out.println(  "IS ALIVE:"+ this.currentThread().isAlive());

                    flagLavora= false;


                }
              System.out.println("-------------------------------------------------------------");


                sleep(1000);



          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }

  System.out.println(  "\n \n EXIT CICLE WHILE \n \n");

      }

THE CONSUMER:
class Consumer extends Thread{

      static int id;
      static Producer produttore=null;
      int code=0;
      BlockingQueue<String> queue;

      public Consumer(BlockingQueue<String> queue,String nameThread, Producer p) {

      super ("THREADN_ "+nameThread);
      this.produttore=p;
      this.queue = queue;
      code=++id;

      }

      public void run(){

        while(true){
          try {


              System.out.println("\n -------------------------------------------------------------");


              System.out.println("CONSUM "+this.getName()+":"+queue.size()+" SIZE QUEUE");
          if (produttore==null){




            stop();


      }         

          else   if (   produttore.getState().compareTo(State.RUNNABLE) ==0  || queue.size()!=0){



     System.out.println( this.getName()+">> "+code+" waiting for the message...");

        String message = queue.take();
        System.out.println("Thread:"+code+" --> "+message+" taken!");

       if (   produttore.getState().compareTo(State.RUNNABLE) ==0  ||  produttore!=null){
          System.out.println("NULL PRODUTTORE + RUNNABLE");

     System.out.println("CONSUMATORE:"+Thread.currentThread().getName()  +"  CHIUDE  \n");
    System.out.println("CONTENUTO PRODUTTORE: "+produttore==null);


        stop();


 }

  System.out.println("------------------------------------------------------------- \n ");


        //riposa 2 secondi
     sleep(2000);   



         }

         else {

             sleep(1000);  
         }




      } catch (InterruptedException e) {
        e.printStackTrace();
        System.err.println("PROBLEMI CONSUMATORE:"+Thread.currentThread().getName());
      }
    }
  }

SO I would like Know how to implement the scenario in while, The producer complished the task to add on a queue strings, and when finished, die, and the consumer works until there is something in the queue condivided and the consumer is alive.

Who could help me?? THANKS

I'm not sure to understand.

You could use the Thread.IsAlive() method to know if your Producer Thread is still alive.

Your while will look like this :

while(produttore.isAlive() || !queue.isempty())

Try to approach the problem in a different way. Instead of a blocking queue, create an Executor (use the helper methods in Executors ).

Then for each task, let the producer submit a task to the executor. Now you can simply wait for the executor to terminate after the producer has submitted all tasks ( ExecutorService.awaitTermination() ).

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