Skip to content

Commit 15c0a66

Browse files
committed
lifecycle of thread
1 parent cb8e9b9 commit 15c0a66

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

src/multithreading/MyThread.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
}

0 commit comments

Comments
 (0)