Results 1 to 9 of 9

Thread: Racing threads

  1. #1
    Arnold is offline Member
    Join Date
    Oct 2009
    Location
    Rotterdam
    Posts
    52
    Rep Power
    0

    Unhappy Racing threads

    I made a test class that will let several threads race against each other.
    In the constructor all the threads are made and started, but they need to start racing when the start() method is called. Until then the threads need to wait in their "Start Positions". Synchronization is not necessary in this situation, but I want to make the threads wait for a common resource. Java doesn't accept that.
    Does anyone know a better alternative?
    PHP Code:
    // No PHP Code! This is Java! I only use it for syntax highlighting.
    // I mean a JAVA forum supports HTML tags and PHP tags, but no JAVA tags?
    // Oh well here is the code:
    
    import java.util.Random;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class Race {
    	public final int numRacers, units, minTimeout, maxTimeout;
    
    	private boolean started = false;
    
    	private final Racer[] racers;
    	private final ExecutorService racePool;
    	private final Random r = new Random();
    	private final Race instance = this;
    
    	public Race(int numRacers, int units, int minTimeout, int maxTimeout) {
    		this.numRacers = numRacers;
    		this.units = units;
    		this.minTimeout = minTimeout;
    		this.maxTimeout = maxTimeout;
    		racers = new Racer[numRacers];
    		racePool = Executors.newFixedThreadPool(numRacers);
    		for (int i = 0; i < numRacers; i++) {
    			racers[i] = new Racer(i + 1);
    			racePool.execute(racers[i]);
    		}
    		racePool.shutdown();
    	}
    
    	public void start() {
    		started = true;
    		System.out.println("Race started");
    //		notifyAll();
    	}
    	public void finish(Racer r) {
    		System.out.println(r + " finished");
    	}
    
    	private class Racer implements Runnable {
    		public final int index;
    		public Racer(int index) {
    			this.index = index;
    		}
    		public void run() {
    			try {
    				// WAIT here until the start() method was called
    //				while (! started)
    //					instance.wait(); // don't know how else to refer to the parent of an inner class...
    				// That didn't work because of an IllegalMonitorStateException
    				System.out.println(this + " started");
    				for (int i = 0; i < units; i++)
    					Thread.sleep(r.nextInt(maxTimeout - minTimeout) + minTimeout);
    				finish(this);
    			} catch (InterruptedException e) {}
    		}
    		public String toString() {
    			return "Racer " + index;
    		}
    	}
    
    	public static void main(String[] args) throws InterruptedException {
    		Race r = new Race(8, 100, 0, 500);
    		Thread.sleep(5000); // wait on purpose before starting the race
    		r.start();
    	}
    }

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,458
    Rep Power
    25

    Default

    I want to make the threads wait for a common resource
    Can you explain a bit?
    After creating all the threads, you can call start() for each in turn.

  3. #3
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    To call Object.wait, Object.notify(), and Object.notifyAll(), you need to have obtained the objects lock first. There may be other methods that need it too, but I don't think there are, and these three are the only ones that are relevant. (Object.notify() is unused in your case, but it's so similar to notifyAll() that I included it. It just makes one thread continue from a wait() call, rather than all of them.)

    Java Code:
    //this is valid
    synchronized(instance){
         obj.notifyAll();
         obj.wait();
    }
    
    //this isn't - you don't hold the objects lock
    obj.notifyAll();
    obj.wait();
    To refer the the instance of the outer class from an inner class, use SuperClassName.this, or in your case, Race.this. Note that this won't work for static inner classes because they are not associated with an instance of the parent. Same thing as the way you can't access 'this' from a static method

    Try adding in the synchronization and making the correct reference to the instance of the outer class. It should help. You probably also want to synchronized the finish(Racer) method, or you could get some very odd output :P the run() method of Racer could probably use just an if(!started) condition as well, rather than a while loop. By the time the wait call returns (because notifyAll() is called) started is set to true, so you don't need to have it be checked again, and it was slightly confusing when I first read the code, so it might help readability a bit too.

    Hope this helps.

    Singing Boyo
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,458
    Rep Power
    25

    Default

    To get the lock for the object obj:
    Java Code:
    synchronized(obj){  // get obj's lock
         obj.notifyAll();
         obj.wait();
    }

  5. #5
    Arnold is offline Member
    Join Date
    Oct 2009
    Location
    Rotterdam
    Posts
    52
    Rep Power
    0

    Default

    Well basicly I want to make multiple threads wait for a singe condition and have all of them resume at the same time when that condition is met.
    I was wondering if this is possible without using locks.

    BTW thanks for the tip on SuperClassName.this.

    I used the while-block to wait, because I read somewhere that wait() does not wait forever.

    Yes I know I could make all threads just start() when the method is called in my example, but what if threads have to wait for this kind of condition mid-progress?

    Right now I see there is a seperate forum for Threads and Synchronization...
    Last edited by Arnold; 06-24-2010 at 02:23 PM.

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,458
    Rep Power
    25

    Default

    multiple threads wait for a singe condition
    Look at the Semaphore class.
    You could hold up the other threads by having 0 permits available until the condition happens. Then if you do a release() of the number of threads waiting on an acquire() they would all be unblocked.

  7. #7
    Arnold is offline Member
    Join Date
    Oct 2009
    Location
    Rotterdam
    Posts
    52
    Rep Power
    0

    Cool

    Quote Originally Posted by Norm View Post
    Look at the Semaphore class.
    You could hold up the other threads by having 0 permits available until the condition happens. Then if you do a release() of the number of threads waiting on an acquire() they would all be unblocked.
    I see! You mean something like this:
    Java Code:
    public Race(int numRacers, int units, int minTimeout, int maxTimeout) {
      //...
      semaphore = new Semaphore(numRacers, true);
      semaphore.drainPermits();
      //...
    }
    
    public void start() {
      started = true;
      System.out.println("Race started");
      s.release(numRacers);
    }
    
    private class Racer implements Runnable {
      //...
      public void run() {
        //...
        s.acquire();
        System.out.println(this + " started");
        //...
      }
      //...
    }
    Thanx

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,458
    Rep Power
    25

    Default

    Yes. Try it and report back how it works.

  9. #9
    Arnold is offline Member
    Join Date
    Oct 2009
    Location
    Rotterdam
    Posts
    52
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Yes. Try it and report back how it works.
    Actually I already did try before posting and it works fine.
    Thanks anyway.

Similar Threads

  1. racing car
    By Patea2000 in forum New To Java
    Replies: 0
    Last Post: 03-07-2010, 09:06 AM
  2. GUI and Threads
    By rp181 in forum Threads and Synchronization
    Replies: 1
    Last Post: 10-10-2009, 08:39 PM
  3. We use Java in creating Racing platform
    By streetsmartchic in forum Reviews / Advertising
    Replies: 0
    Last Post: 12-26-2007, 01:42 AM
  4. Using threads
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-11-2007, 10:25 AM
  5. Threads
    By one198 in forum Threads and Synchronization
    Replies: 1
    Last Post: 11-20-2007, 06:15 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
  •