If you have a program which needs to be doing multiple things at once, you need threads. For example, if you have to draw circles on the screen and at the same time compute fibonacci numbers and print them to the printer from the same program, you don't want to think about the order in which these things happen. Threads allow you to pretend that the CPU is doing multiple things at once, even though it isn't.

1. Implement Runnable (or..)

public class EvilBunnyClass implements Runnable{
       public void run(){
       //this is the method which will get called when you instantiate this class in a thread (see below)
       System.out.println("Evil bunnies hop across the fictitious fields");
       }
}

Somewhere, you have to explicitly start a thread which runs this runnable like this: If you put this code snippet in main(), it will always get executed. You can put this code anywhere, however. The runnable will not start magically even if you instantiate it.

      my_thread = new Thread(new EvilBunnyClass());
      my_thread.start();

2. Subclass Thread

The Thread class itself implements Runnable and has a run() method, so you can override it like this:

public class EvilBunnyThread extends Thread{
  public void run(){
       //this is the method which will get called when you instantiate this class in a thread (see below)
       System.out.println("Evil bunnies hop across the fictitious fields");
       }
}

and then you use it like this:

 
(new EvilBunnyThread()).start();

Thread sleep

You can put your threads to sleep to time events. You can make a thread idle for n milliseconds:

 my_thread.sleep(300);

Thread interruption

*Anyone* can interrupt your thread by calling your_thread.interrupt(). This doesn't actually interrupt the thread; It sets the “interrupted” boolean to “true”. This means that your threads have to check themselves to see if they have been interrupted. more here

Concurrency: are your threads sharing resources ?

Concurrency refers to situations in which multiple things are trying to update/display/read/store etc the same object or variable at the same time.

Links


Personal Tools