File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package multithreading ;
2+
3+ public class MyThread extends Thread {
4+ @ Override
5+ public void run () {
6+ System .out .println ("RUNNING" );
7+ try {
8+ Thread .sleep (2000 );
9+ } catch (InterruptedException e ) {
10+ throw new RuntimeException (e );
11+ }
12+ }
13+
14+ public static void main (String [] args ) throws InterruptedException {
15+ MyThread t1 = new MyThread ();
16+ System .out .println (t1 .getState ()); // NEW
17+ t1 .start ();
18+ System .out .println (t1 .getState ()); // RUNNABLE
19+ // System.out.println(Thread.currentThread().getState()); // RUNNABLE
20+
21+ Thread .sleep (100 );
22+ System .out .println (t1 .getState ()); // TIMED_WAITING
23+
24+ // caller method (main) will wait for t1 to get finished
25+ t1 .join ();
26+ System .out .println (t1 .getState ()); // TERMINATED
27+ }
28+ }
Original file line number Diff line number Diff line change 1+ package multithreading ;
2+
3+ /*
4+ The lifecycle of a thread in Java consists of several state, which a thread can move through during its execution
5+
6+ - New: Created but not started
7+ - Runnable: After the start method is called, the thread becomes runnable.
8+ It's ready to run & is waiting for CPU time.
9+ - Running: When it's executing.
10+ - Blocked/Waiting: When it's waiting for a resource or for another thread to perform an action.
11+ - Terminated: When it has finished executing.
12+ */
13+
14+ public class ThreadLifeCycle {
15+ public static void main (String [] args ) {
16+
17+ World t1 = new World (); // NEW
18+ t1 .start (); // RUNNABLE
19+ System .out .println ();
20+ }
21+ }
You can’t perform that action at this time.
0 commit comments