![]() |
|
Java Threads, Free online Core Java Programming Tutorial, Learn Java Programming Language online for free... |
| Lessons | Java Threads |
|
|
Creating Java Threads There are two ways to create our own Thread object:
Example of Extending Thread public class ThreadExample extends Thread {
public void run () {
for (int i = 1; i <= 100; i++) {
System.out.println(“Thread: ” + i);
}
}
}
Example of Implementing Runnablepublic class RunnableExample implements Runnable {
public void run () {
for (int i = 1; i <= 100; i++) {
System.out.println (“Runnable: ” + i);
}
}
}
It may be noted that both of these are very similar to each other with minor syntactic and semantic differences.
Starting the Threads A thread is started by simply sending the start message to the thread. This is shown in the following example: public class ThreadsStartExample {
public static void main (String argv[]) {
new ThreadExample ().start ();
new Thread(new RunnableExample ()).start ();
}
}
Next >>> Lesson No. 22: Java Threads 2
|