Multithreading

SomeClass class1 = new SomeClass;
SomeClass class2 = new SomeClass;

Thread t1 = new Thread(class1);
Thread t2 = new Thread(class2);

// Start the threads
t1.start();
t2.start();

// Wait until thread 1 is finished before continuing.
t1.join();
// Wait until thread 2 is finished before continuing
t2.join();

System.out.println("Printed after thread 1 and thread 2 are finished.);

Start

  • start() runs a thread.

Join

  • join() blocks the main program the thread is in until it is completed.

Runnable

For a class to be thread-safe and runnable, it needs to implement the Runnable class.

class Train implements Runnable {
...
}

Parallelization Issue

  • When parallelizing using shared data, need to ensure multiple threads don't try to access the memory at the same time
  • Consider
    • Thread A who modifies shared data
    • Thread B whose task adds 2 to shared data

Solution:

  • First one to touch the shared data gets access to it and shared data is locked until it is finished with it. Then it unlocks and allows others to touch the shared data.
    • Downside: Constant locking downgrades performance significantly

Better Solution: Synchronization

  • Java has built-in locking mechanism
  • Every object has an implicit lock associated with it
  • Making a method synchronized causes the method to:
    • Obtain the object's lock before starting method
    • Complete the entire method before releasees the lock
    • If another thread tries to execute the method, it blocks until it can obtain the lock

results matching ""

    No results matching ""