I was today asked in an interview over the Thread concepts in Java? The Questions were...
I did not answer any questions apart from definition of Thread, that too I just learnt from internet.
Can anyone explain me clearly over this.
Update:
What is a difference between a thread and a normal java class. why do we need threading... can i execute business logic in threads. Can i call a different class methods in Threads.
Java offers two types of threads: user threads and daemon threads. User threads are high-priority threads. The JVM will wait for any user thread to complete its task before terminating it. On the other hand, daemon threads are low-priority threads whose only role is to provide services to user threads.
Thread is often referred to as a lightweight process. The process can be split down into so many threads. For example, in a browser, many tabs can be viewed as threads. MS Word uses many threads - formatting text from one thread, processing input from another thread, etc.
Threads allows a program to operate more efficiently by doing multiple things at the same time. Threads can be used to perform complicated tasks in the background without interrupting the main program.
A thread, in the context of Java, is the path followed when executing a program. It is a sequence of nested executed statements or method calls that allow multiple activities within a single process.
To create threads, create a new class that extends the Thread
class, and instantiate that class. The extending class must override the run
method and call the start
method to begin execution of the thread.
Inside run
, you will define the code that constitutes a new thread. It is important to understand that run
can call other methods, use other classes and declare variables just like the main thread. The only difference is that run
establishes the entry point for another, concurrent thread of execution within your program. This will end when run
returns.
Here's an example:
public class MyThread extends Thread {
private final String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
try {
for (; ; ) {
System.out.println(name);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("sleep interrupted");
}
}
public static void main(String[] args) {
Thread t1 = new MyThread("First Thread");
Thread t2 = new MyThread("Second Thread");
t1.start();
t2.start();
}
}
You will see this on the screen:
First Thread
Second Thread
First Thread
Second Thread
First Thread
This tutorial also explains the Runnable
interface. With Spring, you could use a thread pool.
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU. Each part of such program is called a thread. So,
Threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread
class. This class overrides the run()
method available in the Thread
class. A thread begins its life inside run()
method. We create an object of our new class and call start()
method to start the execution of a thread. Start()
invokes the run()
method on the Thread
object.
class MultithreadingDemo extends Thread{
public void run() {
try { // Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e){ // Throwing an exception
System.out.println ("Exception is caught");
}
}
}
public class Multithread{
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<8; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable
interface and override run()
method. Then we instantiate a Thread object and call start()
method on this object.
class MultithreadingDemo implements Runnable{
public void run() {
try { // Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId() +
" is running");
}
catch (Exception e) { // Throwing an exception
System.out.println ("Exception is caught");
}
}
}
class Multithread{
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<8; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
Thread Class vs Runnable Interface
If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With