Defining and Starting a Thread
Defining and Starting a Thread | Javamazon:
'via Blog this'
'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
Runnableobject. 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. TheThreadclass itself implementsRunnable, though itsrunmethod does nothing. An application can subclassThread, providing its own implementation ofrun, 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