可以知道某个Thread是否还活着吗?

时间:2010-12-28 11:18:04

标签: java multithreading

为了我的html解析,我实现了一个PRODUCER / CONSUMER PATTERN。我的问题是我可以在生产者完成任务并且一个缓和的缓冲区之后停止消费者的方式。 实施例:

我有一个生产者和5个消费者。生产者停止工作,因为已经完成了任务。那么消费者怎么知道生产者已经完成了它的工作?  我试着实施:

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());
      }
    }
  }

所以我想知道如何在while中实现场景,生产者完成了添加队列字符串的任务,当完成,死亡,消费者工作直到队列中的某些东西被分割并且消费者是活着。

谁能帮帮我? 致谢

2 个答案:

答案 0 :(得分:2)

我不太明白。

您可以使用Thread.IsAlive()方法来了解您的Producer Thread是否还活着。

您的while将如下所示:

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

答案 1 :(得分:0)

尝试以不同的方式解决问题。而不是阻止队列,创建Executor(使用helper methods in Executors)。

然后,对于每个任务,让生产者向执行者提交任务。现在,您可以在生产者提交所有任务(ExecutorService.awaitTermination())之后等待执行者终止。