Results 1 to 2 of 2
  1. #1
    imorio is offline Senior Member
    Join Date
    Aug 2010
    Posts
    127
    Rep Power
    0

    Default multi-threading problem

    I currently have a piece of code that looks like this in pseudo-code:

    Java Code:
    ArrayList<Foo> fooList=new ArrayList<Foo>();
    while(I need to add more Foo)
    {
    	//make preperations for creating the next Foo
    	
    	[COLOR="Red"]Foo temp=new Foo(add prepared data into the contructor of Foo);[/COLOR]	
    	fooList.add(temp);
    }
    return fooList; when fooList is complete
    The constructor of Foo needs a relatively large amount of time, because of the networking it does. Since I make a lot of Foo, I want to put the red-line into a seperate thread. That way, when one contructor is waiting on getting a response from another server, another Foo constructor can do some work. However I don't want to return untill the list is complete.

    Can anyone give me some pointers to solve this problem?

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

    Default

    I would try to move the network activity outside the constructor of Foo. But if that's not possible, you could do something like this (exception handling omitted):

    Java Code:
    ArrayList<Foo> fooList=new ArrayList<Foo>();
    ArrayList<Thread> tList=new ArrayList<Thread>();
    while(I need to add more Foo)
    {
    	//make preperations for creating the next Foo
    	Thread t = new Thread() {
    		public void run() {
    			Foo temp=new Foo(add prepared data into the contructor of Foo);	
    			fooList.add(temp);
    		}
    	};
    	t.start();
    	tList.add(t);
    }
    for(Thread t : tList) {
    	t.join();
    }
    return fooList; when fooList is complete
    You might have to make fooList final to access it from an inner class. I forget the rules about that.
    Last edited by kjkrum; 04-25-2011 at 06:55 PM.

Similar Threads

  1. Simple question about multi-threading
    By intrepid604 in forum New To Java
    Replies: 0
    Last Post: 03-07-2011, 10:20 PM
  2. Need Help! Multi-Threading question!
    By pinkette in forum New To Java
    Replies: 8
    Last Post: 01-13-2011, 07:08 PM
  3. Problem in Multi threading.
    By Chetans in forum Advanced Java
    Replies: 3
    Last Post: 03-23-2010, 04:42 PM
  4. Newbie to multi-threading please direct me :)
    By kminev in forum Threads and Synchronization
    Replies: 8
    Last Post: 11-18-2009, 06:11 PM
  5. question about Multi threading in Java
    By fred in forum Advanced Java
    Replies: 1
    Last Post: 07-24-2007, 01:55 AM

Posting Permissions

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