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


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

Waiting / Blocking: If a thread is alive, but not eligible to run,
it is said to be in the blocking state.
Dead: When the thread completes its execution, it enters the
dead state.
Write a code sample that creates a thread using the
“Thread” class.
Answer:
The following code creates a thread using “Thread” class:
class MyThread extends Thread {
public static void main(String argument[]) {
MyThread thread = new MyThread ();
thread.start(); // Line 1
}
public void run() {
System.out.println(“Inside Run Method..”);// Line 2
}
}
The code above defines a class called MyThread that extends
the Thread class. When Line 1 is executed, a new thread is
spawned. This executes the code specified within the run()
method.
Write a code sample that creates a thread using the
Runnable interface.


170.
Answer:
The following code creates a thread by implementing the
“Runnable” interface:
class MyThread implements Runnable {
public static void main(String argument[]) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread); //Line 1
thread.start(); // Line 2
}
public void run() {
System.out.println(“Inside Run Method..”);
}
}
The code above defines a class called MyThread that
implements the Runnable interface. A new Thread object is
created and the Runnable implementation that is MyThread
instance is passed to it at line 1. When Line 2 is executed, a new
thread is spawned. This executes the code specified within the
run() method.
Is it possible to create more than one thread in a Java
application? If so, how will the threads communicate with
each other?
Answer:
Yes, it is possible to create more than one thread in a Java
application. For two threads to communicate with each other, the
methods wait(), notify() and notifyAll() from the object
class need to be used.



Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   60   61   62   63   64   65   66   67   ...   171




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