Ans: In Java, 'thread' means two different things:
An instance of Thread is just an object. Like any other object in Java, it has variables and methods and lives and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its own call stack. In Java, there is one thread per call stack or to think of it in reverse, one call stack per thread. Even if you don't create any new threads in your program, threads back there are running.
Ans:
Ans:
Ans: There are two ways to create a new thread. Extend the 'Thread' class and override the 'run()' method in your class. Create an instance of the subclass and invoke the 'start()' method on it, which will create a new thread of execution.
public class NewThread extends Thread
{
public void run()
{
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args)
{
NewThread c = new NewThread();
c.start();
}
}
This will implement the 'Runnable' interface. The class will have to implement the 'run()' method in the 'Runnable' interface. Create an instance of this class. Pass the reference of this instance to the 'Thread' constructor and a new thread of execution will be created.
public class NewThread implements Runnable
{
public void run()
{
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args)
{
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}
}
Ans: With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to erroneous behavior or program.
Ans: A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous when you are going for multiple inheritance.
Ans: Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will execute in same thread, so does not solve the purpose of creating a new thread.
Ans: We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.
Ans: Below are some key points about ThreadLocal variables
ThreadLocal variable are difficult to understand and I recommend you to use best java book on concurrency: Java Concurrency in Practice
Ans: This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.
Ans: Thread.sleep() takes the current thread to a "Not Runnable" state for specified amount of time. The thread holds the monitors it has acquired. For example, if a thread is running a synchronized block or method and sleep method is called then no other thread will be able to enter this block or method. The sleeping thread can wake up when some other thread calls t.interrupt on it. Note that sleep is a static method, that means it always affects the current thread (the one executing sleep method).
A common mistake is trying to call t2.sleep() where t2 is a different thread; even then, it is the current thread that will sleep, not the t2 thread. thread.suspend() is deprecated method. Its possible to send other threads into suspended state by making a suspend method call. In suspended state, a thread keeps all its monitors and can not be interrupted. This may cause deadlocks, therefore, it has been deprecated. object.wait() call also takes the current thread into a "Not Runnable" state, just like sleep(), but with a slight change. Wait method is invoked on a lock object, not thread.
Here is the sequence of operations you can think
Ans: No. If an object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed. See the below sample code which demonstrates it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods
public class Common {public synchronized void synchronizedMethod1() {System.out.println("synchronizedMethod1 called");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("synchronizedMethod1 done");} public synchronized void synchronizedMethod2() {System.out.println("synchronizedMethod2 called");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("synchronizedMethod2 done");}}public class MyThread extends Thread {private int id = 0;private Common common; public MyThread(String name, int no, Common object) {super(name);common = object;id = no;} public void run() {System.out.println("Running Thread" + this.getName());try {if (id == 0) {common.synchronizedMethod1();} else {common.synchronizedMethod2();}} catch (Exception e) {e.printStackTrace();}} public static void main(String[] args) {Common c = new Common();MyThread t1 = new MyThread("MyThread-1", 0, c);MyThread t2 = new MyThread("MyThread-2", 1, c);t1.start();t2.start();}}
Ans: This is very basic threading question. Threads can be created in two ways i.e. by implementing java.lang.Runnable interface or extending java.lang.Thread class and then extending run method.
Thread has its own variables and methods, it lives and dies on the heap. But a thread of execution is an individual process that has its own call stack. Thread are lightweight process in java.
Thread creation by implementingjava.lang.Runnableinterface.
We will create object of class which implements Runnable interface :
MyRunnable runnable=new MyRunnable(); Thread thread=new Thread(runnable);
Ans: Threads are lightweight process only if threads of same process are executing concurrently. But if threads of different processes are executing concurrently then threads are heavy weight process.
Ans: Interviewers tend to know interviewees knowledge about Thread methods. So this is time to prove your point by answering correctly. We can use join() methodto ensure all threads that started from main must end in order in which they started and also main should end in last.In other words waits for this thread to die. Calling join() method internally calls join(0);
Ans: This is very important question, this forms the core of multi threading, you should be able to explain about race condition in detail. When more than one thread try to access same resource without synchronization causes race condition.
So we can solve race condition by using either synchronized block or synchronized method. When no two threads can access same resource at a time phenomenon is also called as mutual exclusion.
Ans:
When notify() method is called on object by thread it notifies all the threads
which are waiting for that object monitor that object monitor is available now.
So, this shows that wait(), notify() and notifyAll() are called on objects only.
Having wait(), notify() and notifyAll() methods means Thread class also must have their monitor.
Every thread having their monitor will create few problems -
>Thread communication problem.
>Synchronization on object won’t be possible- Because object has monitor, one object can have multiple threads and thread hold lock on object by holding object monitor. But if each thread will have monitor, we won’t have any way of achieving synchronization.
>Inconsistency in state of object (because synchronization won't be possible).
Ans: Yes, it’s mandatory to acquire object lock before calling these methods on object. As discussed above wait(), notify() and notifyAll() methods are always called from Synchronized block only, and as soon as thread enters synchronized block it acquires object lock (by holding object monitor). If we call these methods without acquiring object lock i.e. from outside synchronize block then java.lang. IllegalMonitorStateException is thrown at runtime.
Wait() method needs to enclosed in try-catch block, because it throws compile time exception i.e. InterruptedException.
Ans: Thread-safety is a property of an object or code which guarantees that if executed or used by multiple threads in any manner e.g. read vs write it will behave as expected. For example, a thread-safe counter object will not miss any count if same instance of that counter is shared among multiple threads. Apparently, you can also divide collection classes in two category, thread-safe and non-thread-safe. Vector is indeed a thread-safe class and it achieves thread-safety by synchronizing methods which modify state of Vector, on the other hand, its counterpart ArrayList is not thread-safe.
Ans: This is one of the good tricky Java question I have seen in interviews. In simple words, If not caught thread will die, if an uncaught exception handler is registered then it will get a call back. Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException() method, passing the thread and the exception as arguments.
Ans: You can share data between threads by using shared object, or concurrent data structure like BlockingQueue. See this tutorial to learn inter-thread communication in Java. It implements Producer consumer pattern using wait and notify methods, which involves sharing objects between two threads.