Results 1 to 20 of 20
  1. #1
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default Multithreading (Three Threads)

    Hi everybody :)

    I just need your help to teach me how can I programing this example.

    Just explain and guide me to how to program , DON'T give me any solution please :p

    OK, the idea of the program is a three threads they are working together synchronizing.

    the first thread reading data - positive integer numbers - only from the keyboard, entered by a user to be stored in an array -dynamic array -
    Assume that the array can hold all numbers entered without overflow.

    second thread should read data from the array and write them into a file.

    third thread should start reading the array data as well as the file data and display them on the screen in order.

    please I want to understanding how programing this example.
    waiting you.






  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default

    Were you instructed to use three threads? If not, I suggest simplifying. Normally this would call for only one thread. If the objective is to learn about threads and synchronization, perhaps you should start with just two: the main thread, and one other you explicitly create.

    One thread could accept input from the keyboard and store it in the array, and the other could read data from the array and write it to a file. The threads would synchronize on the array. This would be a good opportunity to learn about Object.wait() and Object.notify().

  3. #3
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    thank you Kjkrum, Yes I should use 3 threads.
    I am trying to use wait() and notify() but I don't know how the correct way to use them !

    I try to do first and second thread

    Java Code:
    public class Thread1 extends Thread {
    
        ArrayList s = new ArrayList<Integer>();
        Scanner sc = new Scanner(System.in);
        int num = 0;
    
      public void run(){
    
           System.out.println("Enter a positive number, or negitavie to exit :");
                  while(num >=0){
                         num = sc.nextInt();
                         s.add(num);
                        }
        } 
    }
    second thread
    Java Code:
    public class Thread2 extends Thread  {
        FileOutputStream fp;
        Producer obj1 = null ;
    
      public void run(){
        
          try{
                fp = new FileOutputStream("Q_2.txt");
                new PrintStream(fp).println(obj1.s);
                fp.close();
            }
            catch(IOException e){
            }
        }
    }
    this of course will not work correctly,

    so I need your help, how can I program the third thread which read from the two previous thread and how can I let this 3 thread work together synchronizing ?

  4. #4
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    As a tangent, I'd like to suggest that you implement runnable rather than extend thread. Extension intends you are going to change the abilities of the class somehow, and in these classes you are not. Also, since you can only extend one class it may be more helpful to implement runnable, leaving the ability to extend another class if needed.

    Java Code:
    class MyThreadExample implements Runnable
    Is the change and really doesn't require any changes(it still requires the implementation of run.)

    Implementing vs. Extending(Stackoverflow)

  5. #5
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    thank you sunde887, yes I understand the different between "extends" and "implements",
    thank you,

    any help please ?

  6. #6
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default

    First, give both your threads a reference to the same ArrayList object. Perhaps declare it in your main method, and pass it to your Thread1 and Thread2 classes in their constructors.

    Using wait() and notify() is pretty simple once you understand it. To call either method on an object, a thread must first obtain the lock on that object with synchronized:

    Java Code:
    ArrayList<Integer> list = new ArrayList<Integer>();
    ...
    synchronized(list) {
         // make changes to the list, and then call
         // wait or notify within this synchronized block
    }
    When a thread calls wait() on an object, it automatically releases all its locks and goes to sleep. When another thread calls notify() on that same object, the sleeping thread starts trying to reacquire its locks. Once it acquires all the locks it had before going to sleep, it resumes execution immediately after the call to wait().

    So... your thread that's reading from the ArrayList and writing to the file could synchronize on the list, read everything from it, and then wait() on it, in a loop. The thread that's writing to the list would synchronize on the list, write to it, and call notify() on it, also in a loop.

    Hope that gets you going in the right direction.

  7. #7
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    First, give both your threads a reference to the same ArrayList object. Perhaps declare it in your main method, and pass it to your Thread1 and Thread2 classes in their constructors.
    how can I do that , can you help me please :o ,

  8. #8
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    If they both have an instance variable which is an array list then in main you can pass in the correct array list through a constructor.

    Java Code:
    class X extends Thread{
      ArrayList<SomeType> x;
      public X(ArrayList<SomeType> x){
        this.x = x;
      }
    }
    public class SomeType{
      public static void main(String[] args){
        ArrayList<SomeType> x = new ArrayList<SomeType>();
        X y = new X(x);
      }
    }
    in this example, the thread named y has a reference to the array list.

  9. #9
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    thank you so much sunde887, really helpful :)

    --------

    OK, I am trying to write the first two thread like this

    first one:
    Java Code:
    public class Thread1 extends Thread {
        ArrayList<Integer> ar1 = new ArrayList<Integer>();
        int num = 0;
        public Thread1(ArrayList<Integer> x){
            this.ar1 = x;
        }
         public int scan(){
           Scanner sc = new Scanner(System.in);
                return sc.nextInt();
       }
    
        public void run(){
            System.out.println("Enter a positive number, or negitavie to exit :");
            try{
                num = scan();
                      while(num >=0){
                      ar1.add(num);
                      num = scan();
                      }
            }
            catch(Exception e){
               
            }
        }
    
    }
    second one:
    Java Code:
    public class Thread2 extends Thread {
        PrintWriter fp;
        ArrayList<Integer> ar1 = new ArrayList<Integer>();
        public Thread2(ArrayList<Integer> x){
           this.ar1 = x;
        }
       public void read(){
            try{
                fp = new PrintWriter("Q_2.txt");
            }
            catch(IOException e){
            }
        }
       public void run(){
           read();
           fp.println(ar1);
           close();
       }
       public void close(){
                 fp.close();
            }
    }
    & main:
    Java Code:
    public class Main {
        public static void main(String[] args) {
            ArrayList<Integer> array = new ArrayList<Integer>();
            Thread1 t1 = new Thread1(array);
            Thread2 t2 = new Thread2(array);
            t1.start();
            t2.start();
        }
    
    }
    any one teach me to next steps please :/








    ~
    Last edited by Faith; 05-04-2011 at 01:57 AM.

  10. #10
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default

    Basically what I said earlier:

    Quote Originally Posted by kjkrum View Post
    So... your thread that's reading from the ArrayList and writing to the file could synchronize on the list, read everything from it, and then wait() on it, in a loop. The thread that's writing to the list would synchronize on the list, write to it, and call notify() on it, also in a loop.

  11. #11
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    I am sorry but can you guide me how to do that :( ,,

  12. #12
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I need to preface this with two things, first, a warning: my threading skills are lackluster at best so my help may not be exceptionally great.
    The others thing: you will get more help if you keep trying things and posting your attempts. Read the concurrency section if it helps.

    That being said, here is my advice.

    The thread which reads the input may also maintain it's own personal array to store the data in. If the main array list is not locked it should acquire the lock and add it's personal contents to the main array.

    The thread for writing the array list to the file will want to acquire the lock and then write the array list elements to the file.

    The third thread needs to, when the lock is free, acquire the lock and then print all the contents to the console. You will need to synchronize on the main array. What have you been thinking of trying? What are your doubts? What do you need more clarification on?

    The more specific your question is, the more likely you are to receive more help.

    I wish I could help you more, however; like I said I haven't really gotten into threads, I'll be buying concurrency in practice soon so in two-three months I'll (hopefully) know more.

  13. #13
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    sunde887 & kjkrum - thank you for your help very much.
    if any one have a time and can be with me step by step I will be very thanks to him. I just want understanding deep details to be Professional in java in future.
    only I want understand the concurrent and synchronizing.
    How can I implement that ?
    you said before that using of wait() and notify, and synchronizing the list of array right ? OK, but how ? I put my codes before, is it true where I put array list in main ?
    is it true to create two array list object in all thread class ?

    I apologize that if no one could afford my questions, and I will thankful to you even if you can not help me, just because I am new and beginner in terms of synchronization and I want someone explain to me what I do step by step.

    if any one can afford my questions let's start please from first code I put.
    is it true ?
    should I add any methods ? wait(), notify, or synchronized ?

  14. #14
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default

    Okay, I'll get you started by making some changes to your own Thread1 class.

    Java Code:
    public class Thread1 extends Thread {
        /* don't need to initialize this here, since
        it's initialized in the constructor */
        ArrayList<Integer> ar1; 
        /* moved this here from your scan() method...
        no need to create a new Scanner for every input */
        Scanner sc = new Scanner(System.in);
    
    
        public Thread1(ArrayList<Integer> x){
            this.ar1 = x;
        }
    
    
        public int scan(){
                return sc.nextInt();
        }
    
    
        public void run(){
            System.out.println("Enter a positive number, or negitavie to exit :");
            try{
                      while(!Thread.currentThread().isInterrupted()){
                           int num = scan();
                           if(num < 0)
                                break;
                           synchronized(ar1) {
                                /* this has to be inside the synchronized block, or
                                other threads might not be able to see the change */
                                ar1.add(num);
                                /* tells your other thread, which has called ar1.wait(),
                                to wake up and start reading from ar1 */
                                ar1.notify(); 
                           }
                      }
            }
            catch(Exception e){
               /* it's good to always at least print something
               when you catch an exception. */
               e.printStackTrace(); 
            }
        }
    }
    I haven't tried to compile/run this, so I apologize for any typos.
    Last edited by kjkrum; 05-05-2011 at 11:49 PM.

  15. #15
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    kjkrum thank you very much for your start and now I am very exciting ,,

    I have only one question because other things very understood and code work correctly, thanks kjkrum.

    in this part of code:
    Java Code:
    while(!Thread.currentThread().isInterrupted()){
                           int num = scan();
                           if(num < 0)
                                break;
                           synchronized(ar1) {
                                /* this has to be inside the synchronized block, or
                                other threads might not be able to see the change */
                                ar1.add(num);
                                /* tells your other thread, which has called ar1.wait(),
                                to wake up and start reading from ar1 */
                                ar1.notify();
                           }
                      }
    why you break the loop ? we need to write all number the user is input until he enter negative number the loop break and the second thread is start and run.


    for second thread

    Java Code:
    public class Thread2 extends Thread {
        PrintWriter fp;
        ArrayList<Integer> ar1 = new ArrayList<Integer>();
        public Thread2(ArrayList<Integer> x){
           this.ar1 = x;
        }
       public void read(){
            try{
                fp = new PrintWriter("Q_2.txt");
            }
            catch(IOException e){
            }
        }
       public void run(){
    
          try{
              ar1.wait();
              read();
              fp.println(ar1);
              close();
          }
          catch(Exception e){
    
          }  
       }
       public void close(){
                 fp.close();
            }
    }
    at run() method I am trying to add wait() as you see,
    but the code does not work like I want at all :\
    it does not write the numbers that the user entered.
    Last edited by Faith; 05-06-2011 at 11:22 PM.

  16. #16
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default

    The break is part of the if statement above it.

    You need to synchronize on ar1 before you can call wait() on it. Look at the synchronized block in the code I posted.

  17. #17
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    really great,
    thank you Kjkrum now the idea very clear,
    but when I run the threads, thread which is write the input numbers is write only first number !! why it does not write all list ?

  18. #18
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default

    Could you post the code?

  19. #19
    Faith is offline Member
    Join Date
    Apr 2011
    Posts
    12
    Rep Power
    0

    Default

    this the code :

    Java Code:
     public class Thread2 extends Thread {
        PrintWriter fp;
        ArrayList<Integer> ar1 = new ArrayList<Integer>();
        public Thread2(ArrayList<Integer> x){
           this.ar1 = x;
        }
       public void read(){
            try{
                fp = new PrintWriter("Q_2.txt");
            }
            catch(IOException e){
            }
        }
       public void run(){
    
          try{
              synchronized(ar1){
                 ar1.wait();
              read();
              fp.println(ar1);
              close();
              }
              
          }
          catch(Exception e){
    
          }  
       }
       public void close(){
                 fp.close();
            }
    }

  20. #20
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default

    I see two things wrong with your code:

    1. There's no loop in your run() method.

    2. You're trying to print your numbers by calling PrintWriter.println(Object) with your ArrayList as the argument. I'm not sure what output that will produce, but I'm pretty sure it's not what you want.

Similar Threads

  1. multithreading
    By praveenbhushan1989 in forum Threads and Synchronization
    Replies: 8
    Last Post: 04-17-2011, 03:03 PM
  2. Multithreading Gui
    By BUGSIE91 in forum Threads and Synchronization
    Replies: 7
    Last Post: 10-13-2010, 02:20 PM
  3. Want to know about Multithreading.
    By Chetans in forum Threads and Synchronization
    Replies: 1
    Last Post: 03-19-2010, 07:50 AM
  4. multithreading
    By shilpa.krishna in forum New To Java
    Replies: 2
    Last Post: 06-27-2008, 04:18 PM

Posting Permissions

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