2012-02-26

Java - Threads


// 1. implements Runnable, 2. extend Thread, 3. extend TimerTask 
// *** A thread is born, started, runs, and then dies.

// *** this.yield() -> Causes the currently executing thread object to temporarily pause and allow other threads to execute. 
public final void setDaemon(boolean on)
public final void join(long millisec)
public void interrupt()
public final boolean isAlive()
public static void yield()
public static boolean holdsLock(Object x)

// *** Timer Task
public class GCTask extends TimerTask {
 public void run() {
  System.out.println("Running the scheduled task...");
  System.gc();
 }
}

Timer timer = new Timer();
GCTask task = new GCTask();
timer.schedule(task, 5000, 5000);

// *** Fixed-delay execution. The period is the amount of time between the ending of the previous execution and the beginning of the next execution.
// *** Fixed-rate execution. The period is the amount of time between the start-ing of the previous execution and the beginning of the next execution.

// *** Synchronized
public synchronized void deposit(double amount) {}

public void deposit(double amount) {
 synchronized (this) {
  // ....
  try {
   Thread.sleep(4000);
  } catch (InterruptedException e) {}
 }
}

// *** Deadlock issues --> Ordering Lock
// *** wait() & notify() --> The wait() and notify() methods from the Object class are useful when multiple threads need to access the same data in any type of producer/consumer scenario.

No comments: