java muti threading

Upload: nalluri08

Post on 04-Nov-2015

61 views

Category:

Documents


2 download

DESCRIPTION

Describes how to write multi thread programs in java.

TRANSCRIPT

Mutithreading

MutithreadingJavaProcess vs ThreadA process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one threads invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.

main thread vs worker threads

Thread states

SynchronizationMethod levelclass Methodlevel { //shared among threads SharedResourse x,y; public synchronized void method1() { //multiple threads cannot access concurrently } public synchronized void method2() { //multiple threads cannot access concurrently } public void method3() { //multiple threads can access concurrently }}Block levelClass Blocklevel { //shared among threads SharedResourse x,y; //dummy objects for locking Object xlock = new Object(), ylock = new Object(); public void method1() { synchronized(xlock) { //access x here sequentially (thread safe) } //do something here, but dont access shared resourses x,y because the code here is not thread safe synchronized(xlock) { synchronized(ylock) { // sequential (thread safe) access to x and y } } //do something here, but dont access shared resourses x,y because the code here is not thread safe } // end of method1()} // end of class

Thread classThe class java.lang.Thread has the following constructors:public Thread();public Thread(String threadName);public Thread(Runnable target);public Thread(Runnable target, String threadName);The first two constructors are used for creating a thread by sub-classing the Thread class. The next two constructors are used for creating a thread with an instance of class that implements Runnable interface.

Thread classThe method run() specifies the running behavior of the thread. You do not invoke the run() method explicitly. Instead, you call the start() method of the class Thread. If a thread is constructed by extending the Thread class, the method start() will call back the overridden run() method in the extended class. On the other hand, if a thread is constructed by providing a Runnable object to the Thread's constructor, the start() method will call back the run() method of the Runnable object (and not the Thread's version).Methods of java.lang.Thread classMethod Return Type Description currentThread Thread Returns an object reference to the thread in which it is invoked. getName String Retrieve the name of the thread object or instance. getPriority int Retrieve the thread instance's priority. isAlive boolean Determine if the thread is currently running. run void This method is the entry point for threads, like the main method for applications. start void Start the thread by calling its run method. sleep void Suspend a thread for a specified amount of time (in milliseconds). wait void moves an object into a waiting state where it waits for a lock to be released. notify void Remove a thread from the waiting state and place it in the ready-to-run state. Multi taskingOn systems that have multiple hardware CPUs, mostly server systems, each CPU can run a different thread. If you have multiple tasks, independent of one another, they will complete execution in a shorter period of time since they execute simultaneously. This can be used to great advantage on server systems since incoming client requests are essentially independent of one another. Server applications are intrinsically multi-threaded. In the situation of a single CPU, threads are actually not executed simultaneously(in parallel). Instead, the operating system manages the multiple flow of execution by repeatedly stopping one and starting another. In other words, simultaneous execution is actually an illusion on a single CPU system.

You may be wondering by now why it would be beneficial to simulate simultaneous execution on a single CPU machine. Would it not introduce overheads in switching between the different tasks, and actually take more time to complete all the tasks?

Multi tasking

Advantages of Concurrent executionEach task takes more time to complete than when it has the CPU all by itself. However, each completes in less time than if it were to be second in line in an orderly execution. This is one of the key reasons why it is desirable to use multiple threads even on single CPU machines.

While the CPU runs at a high speed on most modern systems, input and output is still very slow. For example, when your application needs to write data to the disk, it may take a significant time to complete writing. If the entire CPU is halted waiting for this completion and doing nothing else, much of its computation power is just wasted. Using multiple threads enables another flow of execution, not involving the same I/O, to proceed without waiting. This approach maximizes the use of the CPU. Without exception, all modern operating systems are multi-threaded. The Java programming language simply passes on this capability to the application programmer.

Consider the case of the Graphical User Interface (GUI). It has to handle user input at the same time update the graphical display. By using multiple threads, the GUI can stay responsive to the user at any time. Waiting for user input can be a very slow task, when compared to the speed of the CPU, consuming many CPU cycles. By having the CPU switching to another thread, useful work such as updating the display, can be performed while the user is slowly entering the input. Thanks to the use of multiple threads, the GUI system can stay responsive. All modern GUIs use multiple threads during execution.

Concurrency vs ParallelismConcurrent multithreading systems give the appearance of several tasks executing at once, but these tasks are actually split up into chunks that share the processor with chunks from other tasks. In parallel systems, two tasks are actually performed simultaneously. Parallelism requires a multi-CPU system.