We help IT Professionals succeed at work.

Multithreading...

Mike Eghtebas
Mike Eghtebas asked
on
Suppose two car-images are racing (on a frame or on an applet).

Question: How multithreading is applied to it?

I need yet to make the application.

Thank you.
Comment
Watch Question

You could have a separate thread controlling each car if you wish.  They would update the position of the car within the thread and then update the screen with their new locations.

Not really much advantage from doing this with multiple threads, but you could do it that way if you wish to explore threading.
Mike EghtebasDatabase and Application Developer

Author

Commented:
re:> Not really much advantage from doing this with multiple threads

I have an alarm clock application where as the alarm goes of and last for 5 seconds, the alarm screen stops updating second counter. So this means without multithreading, car1 position is visible but not car2. And when car1 stops, then the position of car2 gets updated.

Do you have access to a sample to test?
The key to multi threaded coding is to create a Runnable object:

public class MyJob implements Runnable {
    public AtomicBoolean m_Done = new AtomicBoolean(false) ;

    public void run() {
        while (!m_Done.get()) {
             // Update the position of cars or generally do the work of the thread
         }
   }
}

Then you can execute this Runnable by submitting it to an executor:

int nThreads = 2 ; // Let's use 2 threads
ExecutorService executor = Executors.newFixedThreadPool(nThreads);

MyJob first = new MyJob() ;
MyJob second = new MyJob() ;
executor.execute(first) ;
executor.execute(second) ;

The 'first' and 'second' run() methods will now execute in different threads.

Hope that helps get you started,

Doug