Creating
a new thread is a 3 steps process
Step 1:
Create a class by extending the Thread class
Ex:
class
MyThread extends Thread{
}
Step 2: Override
the run method
Step 3: Call
the start method of the Thread
Example
class MyThread extends Thread{ public void run(){ for(int i=0; i < 5; i++){ System.out.println(i); } } public static void main(String args[]){ MyThread t1 = new MyThread(); t1.start(); } }
Output
0 1 2 3 4
Explanation
MyThread
t1 = new MyThread();
Statement
creates a thread object, and the reference t1 point to the object.
When t1.start() is called it immediately call the run method and
starts execution.
A
Thread is alive until it finishes its execution (A Thread can stop
its execution by calling its stop(), anyway it is deprecated).
Can
I start a Thread twice ?
No
What
will happen if I start a thread twice
Program
will compile fine. But java run time throws
IllegalThreadStateException at run time.
Example
Example
class MyThread extends Thread{ public void run(){ for(int i=0; i < 4; i++){ System.out.println(i); } } public static void main(String args[]){ MyThread t1 = new MyThread(); t1.start(); t1.start(); } }
Sample Output
0 1 2 3 4 Exception in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.start(Unknown Source) at MyThread.main(MyThread.java:13)
You
may not see the output like above when you ran the progrm. Since you
can't expect the output of an Asynchronous program.
Thread
scheduling is non deterministic and depends on many factors,
including what else is currently running in the operating system.
I.e, you can't guess the outcome of threads.
class MyThread extends Thread{ public void run(){ for(int i=0; i < 5; i++){ System.out.println("In My Thread " + i); } } public static void main(String args[]){ MyThread t1 = new MyThread(); t1.start(); for(int i=0; i<5; i++){ System.out.println("In Main Thread " + i); } } }
Possible
outcomes are:
Output
for first run
In Main Thread 0 In Main Thread 1 In My Thread 0 In My Thread 1 In Main Thread 2 In My Thread 2 In Main Thread 3 In My Thread 3 In Main Thread 4 In My Thread 4
Output
for next run
In Main Thread 0 In Main Thread 1 In Main Thread 2 In My Thread 0 In My Thread 1 In Main Thread 3 In My Thread 2 In Main Thread 4 In My Thread 3 In My Thread 4
Threads Create thread by implementing Runnable interface Home
No comments:
Post a Comment