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


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

171.
172.
The wait() method causes the current thread to pause until
some other thread invokes notify on the same object.
If there are many objects that are waiting on a particular object,
the notify() method causes any one thread to resume.
The notifyAll() method causes all the threads that are
waiting on a particular object to resume.
What is Synchronization?
Answer:
When multiple threads try to access a shared resource at the
same time, then they need some way for the resource to be
accessed by only one Thread at a time. The process which helps
to achieve this is called as synchronization. Java provides a
keyword called synchronized which helps to achieve this.
Explain what happens when the following code is
executed.
class TestMyRunnable implements Runnable {
public void run() {
System.out.println(“Inside Run Method..”);
System.out.println(“Name of thread is–
“:Thread.currentThread().getName());
}
}
class TestMyThread {
public static void main(String argument[]) {
TestMyRunnable runnable = new TestMyRunnable();
Thread thread = new Thread(runnable);
Thread.setName(“My Thread”); //Line 1
thread.start(); //Line 2


173.
}
}
Answer:
The code compiles fine and displays the following output:
Inside Run Method.
Name of thread is: My Thread
When Line 1 is executed, it sets the name of the thread to My
Thread. So, when Line 2 is executed, it spawns a new thread
and executes the code within the run() method which prints the
name of the thread as My Thread
Consider the following code:
class TestMyRunnable implements Runnable {
public void run() {
for (int iValue = 0; iValue < 1000; iValue++)
System.out.println(“Name of thread is:
“+Thread.currentThread().getName());
}
public static void main (String argument[]) {
TestMyRunnable runnable = new TestMyRunnable();
Thread threadC = new Thread(runnable);
Thread threadD = new Thread(runnable);
threadC.setName(“Thread 1”);
threadD.setName(“Thread 2”);
threadC.start();
threadD.start();
}
}



Download 1.52 Mb.

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




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