Tips n tricks for Threads

  • Multithreading means multiple lines of a single program can be executed at the same time. The operating system is treating the programs as two separate and distinct processes. 
  • Two ways of creating threads are : implementing an interface and extending a class. 
  • The run() method is where all the work of theCounter class thread is done. 
  • Only classes that implement the Runnable interface (and so are of type Runnable) can be targets of threads.
  • The call to start() will call the target's run() method. The call to start() will return right away and the thread will start executing at the same time.
  • Once a thread is stopped, it cannot be restarted with the start()command, since stop() will terminate the execution of a thread. Instead you can pause the execution of a thread with the sleep()method or temporarily cease the execution using suspend() method and resume() it at later point.
  • Scheduling threads example
  • Which exception might wait() throw? "InterruptedException" or "IllegalMonitorException". 
  • Read about thread in detail here.
  • Typical Producer Consumer example:
class Shared {
int num=0;
boolean value = false;
synchronized int get() {
  if (value==false)
  try {
    wait();
    }
  catch (InterruptedException e) {
     System.out.println("InterruptedException caught");
  }
System.out.println("consume: " + num);
value=false;
notify();
return num;
}
synchronized void put(int num) {
if (value==true)
  try {
    wait();
  }
  catch (InterruptedException e) {
      System.out.println("InterruptedException caught");
  }
    this.num=num;
    System.out.println("Produce: " + num);
    value=false;
    notify();
    }
    }

class Producer extends Thread {
  Shared s;
  Producer(Shared s) {
    this.s=s;
    this.start();
  }
  public void run() {
    int i=0;
    s.put(++i);
    }
}

class Consumer extends Thread{
  Shared s;
  Consumer(Shared s) {
    this.s=s;
    this.start();
  }
  public void run() {
    s.get();
    }}
public class InterThread{
  public static void main(String[] args) 
  {
    Shared s=new Shared();
    new Producer(s);
    new Consumer(s);
  }
}

Comments

Popular posts from this blog

jQgrid reload with new data

Introduction to jQgrid

Rich Client based UI technologies- A Comparison of Thick Client UI tools