2 Replies Latest reply: Mar 14, 2013 3:16 AM by gimbal2 RSS

    Thread Producer and Consumer

    996346
      Hi

      I have an array that keeps Integer into it. what is wrong with this problem i cant fix it. Thread Consumer never start.


      Producer class: Putting nr 1 to 50 int into array eg. 1-2-3-4-5-6-7-8-9-10.....
      Consumer class : removing 50 down to nr 10 from array 50-49-48-47...

      Main Class : Threads creator and starter.

      How can i let Thread P start before C. and when P is finnish it call C, and then C when its done it wakes up P and running like that for life. HOWWW Plz help




      MAIN CLASS:


      import java.util.ArrayList;

      public class Main {

      static ArrayList<Integer> list = new ArrayList<>();

      public static void main(String[] args) {

      Thread p = new Thread(new Producer());
      Thread c = new Thread(new Consumer());

      p.start();
      c.start();

      }

      }











      PRODUCER CLASS:

      public class Producer extends Main implements Runnable{

      @Override
      public void run() {

      while (true) {

      // Tilføjer cornflakes til arrayListen hvis < 10
      if (list.size() <= 10) {

      for (int i = list.size(); i < 50; i++) {

      list.add(i);
      System.out.println("p : " + list.size());

      try {
      Thread.sleep(100);
      } catch (InterruptedException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
      }
      }// end Forloop

      }// end if


      }// end while


      }

      }





      Consumer CLASS


      public class Consumer extends Main implements Runnable {

      @Override
      public synchronized void run() {


      while (true) {

      // Tilføjer cornflakes til arrayListen hvis < 10
      for (int i = list.size(); i > 10; i--) {

      list.remove(i);
      System.out.println("c : " + i);

      try {
      Thread.sleep(100);
      } catch (InterruptedException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
      }
      }// end Forloop

      }// end while

      }

      }
        • 1. Re: Thread Producer and Consumer
          jtahlborn
          your current code indicates that you understand almost nothing of concurrency in java. i suggest you start here:

          http://docs.oracle.com/javase/tutorial/essential/concurrency/
          • 2. Re: Thread Producer and Consumer
            gimbal2
            That's a reason for failure in general by the way - trying to do stuff without understanding stuff. Its best avoided in the future - first learn and learn well, then code. Then when you have problem with said code, come here and ask for help. Not before that, a forum is not a personal information service or substitute teacher.