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.

Difference between Multithreading and Multiprocessing

Multi-threading refers to an application with multiple threads running within a process, while multi-processing refers to an application organised across multiple OS-level processes.
A thread is a stream of instructions within a process. Each thread has its own instruction pointer, set of registers and stack memory. The virtual address space is process specific, or common to all threads within a process. So, data on the heap can be readily accessed by all threads, for good or ill.
Multi-threading is a more "light weight" form of concurrency: there is less context per thread than per process. As a result thread lifetime, context switching and synchronisation costs are lower. The shared address space (noted above) means data sharing requires no extra work.
Multi-processing has the opposite benefits. Since processes are insulated from each other by the OS, an error in one process cannot bring down another process. Contrast this with multi-threading, in which an error in one thread can bring down all the threads in the process. Further, individual processes may run as different users and have different permissions.

Difference between multitasking multiprogramming and multithreading?

Multiprogramming is a rudimentary form of parallel processing in which several programs are run at the same time on a uniprocessor.Since there is only one processor, there can be no true simultaneous execution of different programs. Instead, the operating system executes part of one program, then part of another, and so on. To the user it appears that all programs are executing at the same time.

Multitasking, in an operating system, is allowing a user to perform more than one computer task (such as the operation of an application program) at a time. The operating system is able to keep track of where you are in these tasks and go from one to the other without losing information

Multithreading is the ability of a program or an operating system process to manage its use by more than one user at a time and to even manage multiple requests by the same user without having to have multiple copies of the program running in the computer

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. 

Questions Related to Thread


Q:What’s the difference between Thread and Runnable types?
Ans: 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 to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.


Q: If all methods are synchronized, is a class thread safe?
Ans: Even if all the methods of a class are synchronized, it may still be vulnerable to thread safety problems if it exposes non-final fields or its methods return mutable object references that could be manipulated by multiple threads. Non-final fields should be declared private and encapsulated with synchronization. Rather than return references to internal object fields, create an independent copy that has no relation to the original, known as a deep copy.
A deep copy of an object duplicates the content and state of the original object and all its constituent fields in such a way that none of its properties refer to instances in the original at any level.
These measures will help prevent uncontrolled access to the internal state of objects, but you must also ensure synchronization techniques are applied in a robust, consistent manner that will not cause deadlock or race conditions. It is generally better to use synchronized blocks than synchronized methods for performance reasons. Limit the extent of synchronized blocks and ensure they all use the same object monitor.

Q: 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 calls the run() method of the Runnable type class passed to its constructor. Subclasses of Thread should override the run() method with their own code to execute in the second thread.
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. Howevever, the code will only be executed in a new thread if the start() method is used.


Q: What is a Runnable object and a Runnable argument?
Ans: A Runnable object is one that implements the Runnable interface, which is the type used to execute new threads. The Runnable interface only has one method, run(), which must be implemented by a Runnable class.
In Java an argument is a primitive value or object reference that is passed to a constructor or method, defined in the method signature. A Runnable argument would be a constructor or method argument that is declared to be a Runnable type. The constructor of the Thread class is the most obvious example.
public Thread(Runnable target);
    
This constructor requires a Runnable type argument to be passed when a Thread is instantiated.


Q: 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 a Java program has any concurrent threads, the JVM manages multi-threading behaviour internally rather than use additional 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. These days there is no case where the green thread approach is useful except on systems where this is the only concurrency scheme that is available for Java, on old operating systems and hardware platforms.


Q:What are the daemon threads? 
Ans: Daemon thread are service provider threads run in the background,these not used to run the application code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to complete their execution if all user threads have completed their execution.
To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a user thread use isDaemon() method.
Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution. 


Q:What happens if a start method is not invoked and the run method is directly invoked? 
Ans: If a thread has been instantiated but not started its is said to be in new state. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread. 

ThreadGroup Class - Access Restriction Methods

The ThreadGroup class itself does not impose any access restrictions, such as allowing threads from one group to inspect or modify threads in a different group. Rather the Thread and ThreadGroup classes cooperate with security managers (subclasses of the SecurityManager class), which can impose access restrictions based on thread group membership.

The Thread and ThreadGroup class both have a method, checkAccess, which calls the current security manager's checkAccess method. The security manager decides whether to allow the access based on the group membership of the threads involved. If access is not allowed, the checkAccess method throws a SecurityException. Otherwise, checkAccess simply returns.

The following is a list of ThreadGroup methods that call ThreadGroup's checkAccess before performing the action of the method. These are what are known as regulated accesses, that is, accesses that must be approved by the security manager before they can be completed.
  • ThreadGroup(ThreadGroup parent, String name)
  • setDaemon(boolean isDaemon)
  • setMaxPriority(int maxPriority)
  • stop
  • suspend
  • resume
  • destroy
This is a list of the methods in the Thread class that call checkAccess before proceeding:
  • constructors that specify a thread group
  • stop
  • suspend
  • resume
  • setPriority(int priority)
  • setName(String name)
  • setDaemon(boolean isDaemon)
Related Posts:-

Some Unique Guinness World Records


1,253 Smurfs gathered in the high street in the town of Castleblayney in County Monaghan, Ireland on July 18, 2008. (Guinness World Records)

35,310 Lego Star Wars Clone Troopers in the UK.


The longest skis are 534 m long and were worn by 1,043 skiers in an event organized by Danske Bank on Drottninggatan in Örebro, Sweden, on 13 September 2008.

World's biggest pickup truck - 2002




Surrey resident Sarwan Singh achieved a feat, which every Sikh is going to be proud of. He set a new Guinness Book of World Record by having the longest beard.


The largest pocket knife was designed by Telmo Cadavez and hand made by Virgilio, Raul and Manuel Pires of Portugal. The knife is 3.9m long when open and weighs 122kg.





The largest commercially available hamburger is 74.75 kg (164.8 lbs) and is available for US$399 (£271.55) on the menu at Mallie's Sports Grill & Bar in Southgate, Michigan, USA, as of 29 August 2008.


In Germany, Anita Schwarz set a new record for carrying the most steins of lager over 40m. She staggered across the finishing line holding 19 glasses.


Coke & Mentos Guiness world record With 1,911 explosions in Riga, Latvia.






ThreadGroup Class- Methods that Operate on all Threads within a Group

The ThreadGroup class has three methods that allow you to modify the current state of all the threads within that group:

  • resume
  • stop
  • suspend
These methods apply the appropriate state change to every thread in the thread group and its subgroups.

Related Posts:-

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More