Defining and Starting a Thread

Defining and Starting a Thread | Javamazon:

'via Blog this'


Runnable Object / Subclass Thread
An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:
  • Provide a Runnable object. The Runnable interfacedefines a single method, run, meant to contain the code executed in the thread. The Runnableobject is passed to the Thread constructor, as in the HelloRunnable example:
    public class HelloRunnable implements Runnable {
    
        public void run() {
            System.out.println("Hello from a thread!");
        }
    
        public static void main(String args[]) {
            (new Thread(new HelloRunnable())).start();
        }
    
    }
  • Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:
    public class HelloThread extends Thread {
    
        public void run() {
            System.out.println("Hello from a thread!");
        }
    
        public static void main(String args[]) {
            (new HelloThread()).start();
        }
    
    }
Notice that both examples invoke Thread.start in order to start the new thread.
Refer thread synchronization for further details about thread synchronization process

0 comments:

Post a Comment