Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Download 1.52 Mb.
Pdf ko'rish
bet62/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   58   59   60   61   62   63   64   65   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

162.
a.
b.
CHAPTER
16
Threads
How will you create Threads in Java?
Answer:
There are two ways in which a Thread can be created in Java:
By extending Thread class: In this approach, you need to
create a class that extends the in–built Thread class and you
need to override the run() method. The following code
demonstrates this:
public class MyThread extends Thread {
public void run(){
System.out.println(“In Thread Body..”);
}
}
By implementing the interface called Runnable: In this
approach, you need to create a class that implements the in–
built Runnable interface. The Runnable interface has a single
method called run() which you need to implement. The
following code demonstrates this:
public class MyThread implements Runnable{
public void run(){
System.out.println(“In Thread Body..”);
}
}


163.
164.
165.
Explain the different types of Threads in Java.
Answer:
There are 2 types of threads–User defined Threads and Daemon
threads
User defined threads are those that are created programmatically
by a user. These are high priority threads. The JVM waits for
these threads to finish.
Daemon threads are mostly created by the JVM, although a
user–defined thread can be explicitly set to be a daemon thread
as well. Daemon threads are usually used for background
processes such as Garbage Collection. As soon as all Non–
Daemon threads stop running, the JVM stops running and does
not wait for the Daemon threads to stop.
Can the run method be invoked directly without invoking
the start method?
Answer:
The run() method can directly be invoked instead of invoking
the start() method. However, this will not spawn a new thread,
the code within the run() method will be executed in the same
thread that invokes it. The start() method is responsible for
spawning a new thread and needs to be invoked.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   58   59   60   61   62   63   64   65   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling