Thread in Java (1)
Thread in Java (1)
As we can observe in, the above diagram a thread runs inside the process and
there will be context-based switching between threads there can be multiple
processes running in OS, and each process again can have multiple threads
running simultaneously. The Multithreading concept is popularly applied in
games, animation…etc.
1. Resource Sharing: Threads within the same process share the same
memory space and resources, such as code, data segments, and open files.
This contrasts with processes, which have separate memory spaces. This
shared environment allows for more efficient communication and resource
utilization.
2. Lower Overhead: Creating and managing threads incurs less overhead
compared to processes. Threads require less memory and fewer resources
to manage their execution context (like stack space, registers, etc.) because
they share many of these elements with other threads in the same process.
3. Faster Context Switching: Switching between threads (context switching) is
generally faster than switching between processes. This is because
switching threads does not require the operating system to change the
memory address space, whereas switching processes does.
4. Concurrency: Threads allow for concurrent execution within a single
application, making it easier to perform multiple tasks simultaneously
without the complexity of managing multiple separate processes.
1. Process-Based Multitasking
2. Thread-Based Multitasking
1. Process-Based Multitasking (Multiprocessing)
In this type of Multitasking, processes are heavyweight and each process was
allocated by a separate memory area. And as the process is heavyweight the
cost of communication between processes is high and it takes a long time for
switching between processes as it involves actions such as loading, saving in
registers, updating maps, lists, etc.
2. Thread-Based Multitasking
Now, we can understand why threads are being used as they had the
advantage of being lightweight and can provide communication between
multiple threads at a Low Cost contributing to effective multi-tasking within a
shared memory environment.
There are different states Thread transfers into during its lifetime, let us know
about those states in the following lines: in its lifetime, a thread undergoes the
following states, namely:
1. New State
2. Active State
3. Waiting/Blocked State
5. Terminated State
1. New State
By default, a Thread will be in a new state, in this state, code has not yet been
run and the execution process is not yet initiated.
2. Active State
A Thread that is a new state by default gets transferred to Active state when
it invokes the start() method, his Active state contains two sub-states namely:
given time and it’s the job of the Thread Scheduler to provide the
some short span of time and wait in the runnable state to get their
“Running” state. and after the expiry of its given time slice session, it
again moves back to the “Runnable” state and waits for its next time
slice.
3. Waiting/Blocked State
5. Terminated State
Normally.
As we are familiar, we create Main Method in each and every Java Program,
which acts as an entry point for the code to get executed by JVM, Similarly in
this Multithreading Concept, Each Program has one Main Thread which was
provided by default by JVM, hence whenever a program is being created in
java, JVM provides the Main Thread for its Execution.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().
thread is running...
Sample code to create Threads by Extending Thread Class:
import java.io.*;
import java.util.*;
thread is running...
3) Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the
constructors defined above.
FileName: MyThread1.java
My first thread
FileName: MyThread2.java
// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
My new thread
Now the thread is running ...
Sample code to create Thread by using Runnable Interface:
import java.io.*;
import java.util.*;
Java
1
import java.io.*;
2
import java.util.*;
3
4
public class GFG {
5
public static void main(String args[])
6
{
7
// Thread object created
8
// and initiated with data
9
Thread t = new Thread("Hello Geeks!");
10
11
// Thread gets started
12
t.start();
13
14
// getting data of
15
// Thread through String
16
String s = t.getName();
17
System.out.println(s);
18
}
19
}
Output
Hello Geeks!
Java
1
import java.io.*;
2
import java.util.*;
3
4
public class GFG implements Runnable {
5
public void run()
6
{
7
System.out.println(
8
"Thread is created and running successfully...");
9
}
10
public static void main(String[] args)
11
{
12
// aligning GFG Class with
13
// Runnable interface
14
Runnable r1 = new GFG();
15
Thread t1 = new Thread(r1, "My Thread");
16
// Thread object started
17
t1.start();
18
// getting the Thread
19
// with String Method
20
String str = t1.getName();
21
System.out.println(str);
22
}
23
}
Output
My Thread
Thread is created and running successfully...
Output:
Java
1
import java.io.*;
2
import java.util.*;
3
4
class GFG implements Runnable {
5
public void run()
6
{
7
// implementing try-catch Block to set sleep state
8
// for inactive thread
9
try {
10
Thread.sleep(102);
11
}
12
catch (InterruptedException i1) {
13
i1.printStackTrace();
14
}
15
System.out.println(
16
"The state for t1 after it invoked join method() on
thread t2"
17
+ " " + ThreadState.t1.getState());
18
19
// implementing try-catch block
20
try {
21
Thread.sleep(202);
22
}
23
catch (InterruptedException i2) {
24
i2.printStackTrace();
25
}
26
}
27
}
28
29
// creation of ThreadState class
30
// to implement Runnable interface
31
public class ThreadState implements Runnable {
32
public static Thread t1;
33
public static ThreadState o1;
34
public static void main(String args[])
35
{
36
o1 = new ThreadState();
37
t1 = new Thread(o1);
38
System.out.println("post-spanning, state of t1 is"
39
+ " " + t1.getState());
40
// lets invoke start() method on t1
41
t1.start();
42
// Now,Thread t1 is moved to runnable state
43
System.out.println(
44
"post invoking of start() method, state of t1 is"
45
+ " " + t1.getState());
46
}
47
public void run()
48
{
49
GFG g1 = new GFG();
50
Thread t2 = new Thread(g1);
51
// Thread is created and its in new state.
52
t2.start();
53
// Now t2 is moved to runnable state
54
System.out.println(
55
"state of t2 Thread, post-calling of start() method
is"
56
+ " " + t2.getState());
57
// create a try-catch block to set t1 in waiting
58
// state
59
try {
60
Thread.sleep(202);
61
}
62
catch (InterruptedException i2) {
63
i2.printStackTrace();
64
}
65
System.out.println(
66
"State of Thread t2 after invoking to method sleep()
is"
67
+ " " + t2.getState());
68
try {
69
t2.join();
70
System.out.println(
71
"State of Thread t2 after join() is"
72
+ " " + t2.getState());
73
}
74
catch (InterruptedException i3) {
75
i3.printStackTrace();
76
}
77
System.out.println(
78
"state of Thread t1 after completing the execution
is"
79
+ " " + t1.getState());
80
}
81
}
Output
post-spanning, state of t1 is NEW
post invoking of start() method, state of t1 is RUNNABLE
state of t2 Thread, post-calling of start() method is RUNNABLE
The state for t1 after it invoked join method() on thread t2
TIMED_WAITING
State of Thread t2 after invoking to method sleep() is
TIMED_WAITING
State of Thread t2 after join() is TERMINATED
state of Thread t1 after completing the execution is RUNNABLE
Running Threads
If the class extends the Thread class, the thread can be run by creating
an instance of the class and call its start() method:
Extend Example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
OUTPUT
This code is outside of the thread
This code is running in a thread
If the class implements the Runnable interface, the thread can be run by
passing an instance of the class to a Thread object's constructor and
then calling the thread's start() method:
Implement Example
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
OUTPUT
This code is outside of the thread
This code is running in a thread
The major difference is that when a class extends the Thread class, you
cannot extend any other class, but by implementing the Runnable
interface, it is possible to extend from another class as well, like: class
MyClass extends OtherClass implements Runnable.