Java Threads - Simple Example
public class MyThreadExtendingThread extends Thread{public void run(){
for(int i = 0; i < 100000; i++){
System.out.println("child 1 says - " + i);
}
}
}
public class MyThreadImplementingRunnable implements Runnable{
public void run(){
for(int i = 0; i < 100000; i++){
System.out.println("child 2 says - " + i);
}
}
}
public class ThreadTester {
public static void main(String[] args) {
/* Ok think of a thread as a child in your class. You ask the child
to count from 0 to 100000. You as the teacher starts counting with the child.
But you two count on two different "threads" so you don't have to wait till
the kid is finish counting.
Let's see this in java - run and see
*/
//MyThreadExtendingThread extends java.lang.Thread class
MyThreadExtendingThread t1 = new MyThreadExtendingThread(); // create a kid to count
t1.start(); // ask the kid to start his job (in this case counting)
/*MyThreadImplementingRunnable implements java.lang.Runnable interface
so if you have to create an instance out of java.lang.Thread class
and pass an instance of your MyThreadImplementingRunnable to it. Then call start()
method of the java.lang.Thread instance
*/
Thread t2 = new Thread(new MyThreadImplementingRunnable()); // create another kid
t2.start(); // ask the kid to start his job (in this case counting)
// you also start counting
for(int i = 0; i < 100000; i++){
System.out.println("Teacher says - " + i);
}
}
}
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment