Java Thread By Extending Thread Class
- A thread can be created in java by extending Thread class, where you must override run() method.
- Call start() method to start executing the thread object.
Thread Sample Code
Code: |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package com.myjava.threads;
class MySmpThread extends Thread{
public static int myCount = 0 ;
public void run(){
while (MySmpThread.myCount <= 10 ){
try {
System.out.println( "Expl Thread: " +(++MySmpThread.myCount));
Thread.sleep( 100 );
} catch (InterruptedException iex) {
System.out.println( "Exception in thread: " +iex.getMessage());
}
}
}
}
public class RunThread {
public static void main(String a[]){
System.out.println( "Starting Main Thread..." );
MySmpThread mst = new MySmpThread();
mst.start();
while (MySmpThread.myCount <= 10 ){
try {
System.out.println( "Main Thread: " +(++MySmpThread.myCount));
Thread.sleep( 100 );
} catch (InterruptedException iex){
System.out.println( "Exception in main thread: " +iex.getMessage());
}
}
System.out.println( "End of Main Thread..." );
}
}
|
|
Example Output
Starting Main Thread...
Main Thread: 1
Expl Thread: 2
Expl Thread: 3
Main Thread: 4
Expl Thread: 5
Main Thread: 5
Expl Thread: 6
Main Thread: 7
Main Thread: 8
Expl Thread: 9
Expl Thread: 11
Main Thread: 10
End of Main Thread...
- See more at: http://www.java2novice.com/java_thread_examples/extending_thread_class/#sthash.Fdz3QuUe.dpuf
No comments:
Post a Comment