Sunday, May 6, 2012

JAVA Thread

I did some work on JAVA Thread this week. I found two ways to use thread in JAVA.

public class ThreadA extends Thread{
   public void run(){
      //code
   }
}

public class ThreadB implements Runnable{
   public void run(){
      //code
   }
}

I wrote a piece of code with the first method.


class MyThread extends Thread{
        private int threadID;
        public MyThread(int id){
            this.threadID=id;
        }
        public void run(){
            int random = (int)(Math.random()*10000);
            try
            {
                Thread.sleep(random);
                jTextArea1.append("thread: "+this.threadID+" slept "+random+"ms"+"\n");
                jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength() - 1);
            }
            catch(Exception e)
            {
                System.err.println(e.toString());
                System.exit(1);
            }
        }
    }

private void StartActionPerformed(java.awt.event.ActionEvent evt) {
        num_of_client = Integer.parseInt(jTextField1.getText());     
        for (int i=0;i<num_of_client;i++){
            t.add(new MyThread(i));
            t.get(i).start();
}
The output of above code looked like:
thread: 4 slept 1204ms
thread: 7 slept 2472ms
thread: 6 slept 4397ms
thread: 9 slept 6533ms
thread: 3 slept 7535ms
thread: 5 slept 7589ms
thread: 2 slept 8443ms
thread: 1 slept 8455ms
thread: 8 slept 9379ms
thread: 0 slept 9457ms
  

I was not clear what the difference between those two methods. According to the JAVA api, The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.


Normally the better way is implementing Runnable interface, because if the thread class you are creating is to be subclass of some other class, it can’t extend from the Thread class. This is because Java does not allow a class to inherit from more than one class. In such a case one can use Runnable interface to implement threads.

No comments:

Post a Comment