Question 1. What is difference between these two way of writing Thread?
public class ThreadA implements Runnable {
public void run() {
//Code
}
}
//with a "new Thread(threadA).start()" call
public class ThreadB extends Thread {
public ThreadB() {
super("ThreadB");
}
public void run() {
//Code
}
}
Answers : understand Extending v/s Implementing Thread_
Extends binds two class files very closely and can cause some pretty hard to deal with code.
Both approaches do the same job but there have been some differences.
The most common difference is
1. When you extends Thread class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class).
2. When you implements Runnable, you can save a space for your class to extend any other class in future or now.
However, one significant difference between implementing Runnable and extending Thread is that
by extending Thread, each of your threads has a unique object
associated with it, whereas implementing Runnable, many threads can share the
same object instance.
associated with it, whereas implementing Runnable, many threads can share the
same object instance.
If there is private variable as private int counter = 0;
Below will be output for implementing runnable vs extending thread.
ImplementsRunnable : Counter : 1
ImplementsRunnable : Counter : 2
ImplementsRunnable : Counter : 3
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1
Point to Note :
A class that implements Runnable is not a thread and just a class. For a Runnable to become a Thread, You need to create an instance of Thread and passing itself in as the target.
like below :
ImplementsRunnable rc = new ImplementsRunnable();
Thread t1 = new Thread(rc); t1.start();
Answer :
Executor executor = Executors.newFixedThreadPool(n);
Runnable runnable = new Runnable() {
public void run() {
// do your thing here
}
}
executor.execute(runnable);
more answers :
- In Java 5, Executor framework was introduced with the java.util.concurrent.Executor interface.
- The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.
- Creating a lot many threads with no bounds to the maximum threshold can cause application to run out of heap memory.
- So, creating a ThreadPool is a better solution as a finite number of threads can be pooled and reused.
- Executors framework facilitate process of creating Thread pools in java.
Question 3: How many types of executor are there so we can run question 2 in different style .
Answer :
there are many like newFixedThreadPool , newCachedThreadPool,
Question 4: what is daemon thread in java ?
Answer :
A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.
setDaemon(true/false) ? This method is used to specify that a thread is daemon thread.
public boolean isDaemon() ? This method is used to determine the thread is daemon thread or not.
Daemon Thread creation example are below :
public class DaemonThread extends Thread {
public void run() {
System.out.println("Entering run method");
try {
System.out.println("In run Method: currentThread() is" + Thread.currentThread());
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException x) {}
System.out.println("In run method: woke up again");
}
} finally {
System.out.println("Leaving run Method");
}
}
public static void main(String[] args) {
System.out.println("Entering main Method");
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
try {
Thread.sleep(3000);
} catch (InterruptedException x) {}
System.out.println("Leaving main method");
}
}
More Information About Daemon Thread :
Java has a special kind of thread called daemon thread.
- Very low priority.
- Only executes when no other thread of the same program is running.
- JVM ends the program finishing these threads, when daemon threads are the only threads running in a program.
What are daemon threads used for?
Normally used as service providers for normal threads. Usually have an infinite loop that waits for the service request or performs the tasks of the thread. They can’t do important jobs. (Because we don't know when they are going to have CPU time and they can finish any time if there aren't any other threads running. )
A typical example of these kind of threads is the Java garbage collector.
There's more...
- You only call the setDaemon() method before you call the start() method. Once the thread is running, you can’t modify its daemon status.
- Use isDaemon() method to check if a thread is a daemon thread or a user thread.
Question 5: The difference between the Runnable and Callable interfaces in Java ?
Answer : we have example of lots of runnable interface above.
The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
Callable example :
class Task implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
return "Ready!";
}
}
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Task());
try {
System.out.println("Started..");
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
Question 6: Difference between sleep vs wait ?
Answer
Sleep
- mainly used for Polling to external / internal system, Or to fetch / check for certain results from other system at regular interval.
|
Wait
- Used in system level synchronization & avoid race-conditions.
|
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanos) throws InterruptedException
|
public final void wait() throws InterruptedException
public final void wait(long timeout, int nanos) throws InterruptedException
public final void wait(long timeout) throws InterruptedException
|
Thread.sleep() method can be used alone, It does not require to be used in conjuction with notify() / notifyAll() methods.
|
We need to use wait() method in conjuction with notify() / notifyAll() methods. We also have wait() method with timeout but that is rarely useful.
|
sleep() method belongs to Thread class.
|
wait() method belongs to Object class.
|
Important : Why wait and notify method are in Object class ?
- As these methods operates of the common property ( lock / monitor property ) of any object, They are part of Object class not the Thread class.
- In multi threaded program, You can have any object as your shared object, On which current executing thread would acquire a lock / monitor first & then execute further.
Question 7: Use of join method ?
Ordered Execution of thread…...T1 & T2 in parallel, once T1 & T2 is done. go for T3.
This method is useful to manage co-related / inter-dependant tasks and functionalities implementation with multiple threads.
- For example,
- If I've three different tasks to execute - T1, T2 & T3 ; Among these tasks I want T1 & T2 to execute in parallel by two different threads.
- But T3 is depedent on T1 & T2 both so T3 tasks should be executed only after completion of T1 & T2.
- So for such kind of scenario I can use join() method call for T1 & T2 before starting thread for T3 thread.
public class Thread_Join_Demo {
public static void main(String[] args) {
Thread thread1 = new MyThread("Task-1");
Thread thread2 = new MyThread("Task-2");
Thread thread3 = new MyThread("Task-3");
// starting threads to complete task 1 & 2
thread1.start();
thread2.start();
// waiting until task 1 & 2 gets completed
// And it's respective threads died.
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// starting task 3 only after completion
// of tasks 1 & 2.
thread3.start();
// wait until task3 completes
try {
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Question : How to get thread state in java ?
Thread.State currThreadState = Thread.currentThread().getState();
System.out.println("Current thread state is : " + currThreadState.name());
Thread can on on any of the BLACK dot point.
Question : What is realtime use of yield method ?
Usually very rare applications require use of yield() method
- It causes the current thread object to pause temporarily and allow the other runnable threads to execute.
- Thread can voluntarily relinquish control on execution of yield() method, It changes its state from running state to runnable state.
- In other words, You can also say : "The calling thread voluntarily yields the CPU to another runnable threads".
Question: Difference between synchronized block and synchronized method in Java ?
Sychronize method is more expensive than synchronized block in terms of performance.
|
Sychronized block is less expensive than synchronized method in terms of performance.
|
Compiler creates less bytecode for a synchronized method.
|
Compiler creates more bytecode for a synchronized block.
|
Entire method becomes the critical section.
|
Only the part / block of the method becomes critical section.
|
Analysis pending ????
Question : what is count down latch ?
Question : What are Concurrent Collection Classes ?
Thread local
how to catch exception from thread
Analysis pending :
No comments:
Post a Comment