Monday, November 5, 2012

Core Java 63 Thread Interview Questions


Thread Interview Questions


1) What is threaded programming and when is it used?


Ans. Threaded programming is normally used when a program is required to do more than one task at the same time. A new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction.

2) Why are there separate wait and sleep methods?


Ans. The static Thread.sleep(long) method maintains control of thread execution but delays the next action until the sleep time expires. The wait method gives up

control over thread execution indefinitely so that other threads can run.

3) What’s the difference between Thread and Runnable types?


Ans: A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method.

The Thread class: provides a mechanism for the first thread to start-up other threads to run in parallel with it.


The Runnable interface: defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to fulfill by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.

4) How does the run() method in Runnable work?


Ans: It may help to think of the run method like the main method in standard single threaded applications. The run method is a standard entry point to run or execute a Thread class. The run method is normally only executed in the context of an independent Thread, but is a normal method in all other respects.

5) A Thread is runnable, how does that work?


Ans: The Thread class’ run method normally invokes the run method of the Runnable type it is passed in its constructor. However, it is possible to override the thread’s run method with your own.

6) What’s the difference between a thread’s start() and run() methods?

Ans: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.
The Thread class’ run() method does nothing, so sub-classes should override the
method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread’s run() method executes the run() method of
the Runnable object in the new thread instead.


Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

7) Can I implement my own start() method?


Ans: The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialized. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method.

8) Which class is the wait() method defined in?


Ans: The wait() method is defined in the Object class, which is the ultimate superclass of all others. So the Thread class and any Runnable implementation inherit this method from Object. The wait() method is normally called on an object in a multi-threaded program to allow other threads to run. The method should only be called by a thread that has ownership of the object’s monitor, which usually means it is in a synchronized method or statement block.

9) What is a green thread?


Ans. A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If the Java program has any concurrent threads, the JVM manages multi-threading internally rather than using other operating system threads.
There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and removed from more recent Java implementations. Current JVM implementations make more efficient use of native operating system threads.

10) What is thread?


Ans. A thread is a lightweight sub process. It is a separate path of execution. It is called separate path of execution because each thread runs in a separate stack frame.

11) What is the difference between preemptive scheduling and time slicing?

Ans: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

12) What does join() method?

Ans. The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

13) Is it possible to start a thread twice?


Ans. No, there is no possibility to start a thread twice. If we do, it throws an exception.

14) Can we call the run() method instead of start()?


Ans. Yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads.

15) What about the daemon threads?


Ans. The daemon threads are basically the low priority threads that provide the background support to the user threads. It provides services to the user threads.

Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.

16) What is shutdown hook?


Ans. The shutdown hook is basically a thread i.e. invoked implicitly before JVM shuts down. So we can use it perform clean up resource.

17) What is synchronization?

Ans. Synchronization is the capability to control the access of multiple threads for any shared resource. It is used:

    To prevent thread interference.

    To prevent consistency problem.

18) What is the purpose of Synchronized block?


Ans. Synchronized block is used to lock an object for any shared resource.

    Scope of synchronized block is smaller than the method.

19) Can Java object be locked down for exclusive use by a given thread?


Ans. Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

20) What is static synchronization?

Ans. If you make any static method as synchronized, the lock will be on the class not on object.

21) What is the difference between notify() and notifyAll()?



Ans. notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

22) What is deadlock?



Ans. Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource, which is held by the other waiting thread.

23) What is gc()?



Ans. gc() is a deamon thread. gc() method is defined in System class that is used to send request to JVM to perform garbage collection.

24) Why JVM terminates the daemon thread if there is no user thread remaining?


Ans. The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.


25) Who makes your class object as thread object?

Ans. Thread class constructor allocates a new thread object. When you create object of your thread class, your class constructor is invoked (provided by Compiler) from where Thread class constructor is invoked (by super() as first statement). So your class object is thread object now.


26) Explain me the diff between :


          public void join()throws InterruptedException and

          public void join(long miliseconds)throws InterruptedException

Ans. In first the thread will wait till the thread on which join is called finished its execution, while in second case the calling thread will start its operation after given time, even the joined thread has completed its work or not. 

27) What addShutDownHook() method do?


Ans. The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing clean resource means closing log file, sending some alerts or something else. So if you want to execute some code before JVM shuts down, use shutdown hook.

addShutdownHook(Runnable r) method:


The addShutdownHook() method of Runnable class is used to register the thread with the Virtual Machine. Syntax:

 
public void addShutdownHook(Runnable r){}
Exp: class MyThread extends Thread{
               public void run(){
                               System.out.println("shut down hook task completed..");
               }
}
public class Shutdown {
public static void main(String[] args)throws Exception {
Runtime r=Runtime.getRuntime();
r.addShutdownHook(new MyThread());
System.out.println("Now main sleeping... press ctrl+c to exit");
try{Thread.sleep(3000);}catch (Exception e) {}
}}

28) What is Lock?

Ans. Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.


29) Problem without static synchronization


Ans. Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.


Thread

Object1.method()

Object2.method()

t1 = new Thread(Object1)

Have lock

Can run

t2 = new Thread(Object1)

Can’t run

Can run

t3 = new Thread(Object2)

Can run

Have lock

t4 = new Thread(Object2)

Can run

Can’t run


 In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.


But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.


If I want no interference between t1 and t3 or t2 and t4. Static synchronization solves this problem.


30) What is synchronization in respect to multi-threading in Java?


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 of program.

31) Why do we need run() & start() method both. Can we achieve it with only run method?


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.


32) What is the difference between sleep(), suspend() and wait() ?


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 locked object, not thread.

Here is the sequence of operations you can think

  • A thread T1 is already running a synchronized block with a lock on object - lets say "lockObject"
  • Another thread T2 comes to execute the synchronized block and find that it’s already acquired.
  • Now T2 calls lockObject.wait() method for waiting on lock to be release by T1 thread.
  • T1 thread finishes all its synchronized block work.
  • T1 thread calls lockObject.notifyAll() to notify all waiting threads that its done using the lock.
  • Since T2 thread is first in the queue of waiting it acquires the lock and starts processing.

33) Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed?


Ans. Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized.

34) Can two threads call two different synchronized instance methods of an Object?


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 demonstrate it very clearly.

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();
}
}
 

OutPut:


Running ThreadMyThread-1

synchronizedMethod1 called

Running ThreadMyThread-2

synchronizedMethod1 done

synchronizedMethod2 called

synchronizedMethod2 done
 
It is clear that only one synchronized instance method is called at a time until and unless it completes its working the other instance method is not called.

35)What is Starvation? and What is a Livelock?


Ans. Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.

LiveLock


Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:

  • When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
  • When all the threads in a program are stuck in infinite loops.

Starvation


Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.

36) How will you take thread dump in Java? How will you analyze Thread dump?


Ans. A Thread Dump is a complete list of active threads. A java thread dump is a way of finding out what each thread in the JVM is doing at a particular point of time. This is especially useful when your java application seems to have some performance issues. Thread dump will help you to find out which thread is causing this. There are several ways to take thread dumps from a JVM. It is highly recommended to take more than 1 thread dump and analyze the results based on it.

37) What is a thread leak? What does it mean in Java?


Ans. Thread leak is when a application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang

38) What is thread pool? Why should we use thread pools?


Ans. A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment. One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Below are key reasons to use a Thread Pool

  • Using thread pools minimizes the JVM overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead.
  • You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).

Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.

39) Can we synchronize the run method? If yes then what will be the behavior?


Ans. Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object

40) Explain how you would get a Thread Deadlock with a code example?

Ans. The example below causes a deadlock situation by thread-1 waiting for lock2 and thread-0 waiting for lock1.





package com.sushil.thread;

public class DeadlockTest extends Thread {

    public static Object lock1 = new Object();
    public static Object lock2 = new Object();

    public void method1() {
        synchronized (lock1) {
              try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("method1: " + Thread.currentThread().getName());
            synchronized (lock2) {
                System.out.println("method1 is executing .... ");
            }
        }
    }

    public void method2() {
        synchronized (lock2) {
              try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("method2: " + Thread.currentThread().getName());
            synchronized (lock1) {
                System.out.println("method2 is executing .... ");
            }
        }
    }

    @Override
    public void run() {
        method1();
        method2();
    }

    public static void main(String[] args) {
        DeadlockTest thread1 = new DeadlockTest();
        DeadlockTest thread2 = new DeadlockTest();

        thread1.start();
        thread2.start();
    }
    
}


The output will be something like:

method1: Thread-1

method1 is executing ....

method1: Thread-0

method2: Thread-1




41) Why wait, notify, and notifyall methods are defined in the Object class, and not in the Thread class?

Ans. Every Java Object has a monitor associated with it. The threads using that object can lock or unlock the monitor associated with the object. Wait and notify/notifyAll methods are responsible for acquiring and relinquishing the lock associated with the particular object. Calling wait causes the current thread to wait to acquire the lock of the Object, and calling notify/notifyAll relinquishes the lock and notify the threads waiting for that lock.


42) Write One program for Cosumer-Producer Problem?

Ans.

 package com.in.thread;



class ProducerConsumer{

           private int count;

           public synchronized void consume(){

              if(count==0){

                    try{

                              wait();

                         }catch(Exception e){e.printStackTrace();}

               }

               System.out.println("Consume() --"+ count);

               count--;

                try{

                        Thread.sleep(1000);

                 }catch(Exception e){

                         e.printStackTrace();

                 }

            }

            public synchronized void produce(){

                    System.out.println("produce() --"+ count++);

                    notifyAll();

            }
}

public class ProducerConsumerTest implements Runnable{

            ProducerConsumer pc1;

            boolean isConsume;

            int i=0;

            public ProducerConsumerTest(ProducerConsumer pc, boolean c){

                   this.pc1=pc;

                   this.isConsume=c;

            }

            public static void main(String[] args) {

                       

                        ProducerConsumer pc=new ProducerConsumer();

                        Thread pro=new Thread(new ProducerConsumerTest(pc,false));

                        Thread con=new Thread(new ProducerConsumerTest(pc,true));

                        pro.start();

                        con.start();

            }

            public void run() {

                        for(;i<10;i++){

                                    if(i%2==0){

                                                pc1.produce();

                                    }else

                                    {

                                                pc1.consume();

                                    }

                        }

            }

}



43) Thread.yield() Vs Thread.sleep() ?


Ans. yield(): Causes the currently executing thread object to temporarily pause and allow other threads to execute.
sleep(long millis) or sleep(long millis,int nanos)
Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds.

44) What are different ways in which a thread can enter the waiting state?

Ans. A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an object's lock
4. By invoking an object's wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.

45) How to create multithreaded program? Explain different ways of using thread? When a thread is created and started, what is its initial state?
                                                                  OR
Extending Thread class or implementing Runnable Interface. Which is better?

Ans. You have two ways to do so. First, making your class "extends" Thread class. The other way is making your class implement "Runnable" interface. The latter is more advantageous, because when you are going for multiple inheritance, then only interface can help. . If you are already inheriting a different class, then you have to go for Runnable Interface. Otherwise you can extend Thread class. Also, if you are implementing interface, it means you have to implement all methods in the interface. Both Thread class and Runnable interface are provided for convenience and use them as per the requirement. But if you are not extending any class, better extend Thread class as it will save few lines of coding. Otherwise performance wise, there is no distinguishable difference. A thread is in the ready state after it has been created and started.

46) What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
Ans. Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.

47) What is daemon thread and which method is used to create the daemon thread?
Ans. Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread. These threads run without the intervention of the user. To determine if a thread is a daemon thread, use the accessor method isDaemon()
When a standalone application is run then as long as any user threads are active the JVM cannot terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads.

48) What is an object's lock and which objects have locks?
Ans. An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

49) Can a lock be acquired on a class?
Ans. Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

50) Is there a separate stack for each thread in Java?
Ans. Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations,
called activation records or stack frame. The activation record contains pertinent information about a method like local variables.
51) Can the variables or classes be Synchronized?

Ans. No. Only methods can be synchronized.

52) How many locks does an object have?
Ans. Each object has only one lock.

53) What all constructors are present in the Thread class?
Ans. Thread()
 Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)

54) When jvm starts up, which thread will be started up first?
Ans. When jvm starts up the thread executing main method is started.

55) If code running is a thread creates a new thread what will be the initial priority of the newly created thread?
Ans. When a code running in a thread creates a new thread object, the priority of the new thread is set equal to the priority of the thread which has created it.

56) What happens when start() is called?
Ans. A new thread of execution with a new call stack starts. The state of thread changes from new to runnable. When the thread gets chance to execute its target run() method starts to run.

57) What is a volatile keyword?
Ans. In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also has performance issues.

58) What is the difference when the synchronized keyword is applied to a static method or to a non static method?
Ans. when a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class don’t interfere with each other. It means, a thread accessing a synch non static method, then the other thread can access the synch static method at the same time but can’t access the synch non static method.

59) What are the different states of a thread's lifecycle?
Ans. The different states of threads are as follows:
1) New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
2) Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
3) Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
 4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked. 5)      Dead – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.





60) What are the two ways of creating thread?
Ans) There are two ways to create a new thread.
1) 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. e.g.
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();
}

}

2) Implements 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 a new thread of execution will be created. e.g. class
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();
}

}

61) What are the advantages or usage of threads?
Ans. Threads support concurrent operations. For example,
 • Multiple requests by a client on a server can be handled as an individual client thread.
 • Long computations or high-latency disk and network operations can be handled in the background without disturbing foreground computations or screen updates.

Threads often result in simpler programs.
• In sequential programming, updating multiple displays normally requires a big while-loop that performs small parts of each display update. Unfortunately, this loop basically simulates an operating system scheduler. In Java, each view can be assigned a thread to provide continuous updates.
• Programs that need to respond to user-initiated events can set up service routines to handle the events without having to insert code in the main routine to look for these events.

Threads provide a high degree of control.
• Imagine launching a complex computation that occasionally takes longer than is satisfactory. A "watchdog" thread can be activated that will "kill" the computation if it becomes costly, perhaps in favor of an alternate, approximate solution. Note that sequential programs must muddy the computation with termination code, whereas, a Java program can use thread control to non-intrusively supervise any operation.

Threaded applications exploit parallelism.
• A computer with multiple CPUs can literally execute multiple threads on different functional units without having to simulating multi-tasking ("time sharing").
• On some computers, one CPU handles the display while another handles computations or database accesses, thus, providing extremely fast user interface response times.


62) What is difference between thread and process?
Ans. Differences between threads and processes are:-
1. Threads share the address space of the process that created it; processes have their own address.
2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent process.
6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process do not affect child processes.