2. What is a Thread?
A thread of
execution is the
smallest
sequence of
programmed
instructions
that are
managed by a
process.
A process can have
multiple threads
whereas vice versa is
not true.
3. Thread States
A thread state. A thread can be in one of the following states:
NEW: A thread that has not yet started is in this state.
RUNNABLE: A thread executing in the Java virtual machine is in this state.
BLOCKED: A thread that is blocked waiting for a monitor lock is in this state.
WAITING :A thread that is waiting indefinitely for another thread to perform
a particular action is in this state.
TIMED_WAITING: A thread that is waiting for another thread to perform an
action for up to a specified waiting time is in this state.
TERMINATED: A thread that has exited is in this state.
A thread can be in only one state at a given point in time.
These states are virtual machine states which
do not reflect any operating system thread
states.
4. Hello World program uses Threads.
When the JVM starts, it creates a thread called "Main". Your program will
run on this thread, unless you create additional threads yourself.
The first thing the "Main" thread does is to look for your static void
main(String[] argv) method and invoke it. That is the entry-point to your
program.
If you want things to happen "at the same time", you can create multiple
threads, and give each something to execute. They will then continue to do
these things concurrently. The JVM also creates some internal threads for
background work such as garbage collection.
6. Ways to create a Thread.
1 : implement the Runnable
class.
2 : extend the Thread class.
Example posted at URL:
https://github.com/Pradhan10/threads-
explained/tree/master
7. Pop Quiz
Why did the second example using extnds Thread class not
print child thread name ?
8. Take a closer look
/* This example illustrates creation of thread by extending Thread class.
* Author : Pradhan Rishi Sharma
* Email : pradhanrishi10@gmail.com
*/
public class HelloThread extends Thread {
public void run() {
Thread child = Thread.currentThread();
child.setName("Child");
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
Thread main = Thread.currentThread();
System.out.println("Hello from main"+" "+main);
(new HelloThread()).start();
}
}
10. Can anyone guess a problem with
threads ?
If not , the presentation is over !
Example problem URL
: https://github.com/Pradhan10/threads-
explained/blob/master/TestThread.java