You are on page 1of 12

Mutithreading

Java

Process vs Thread
A 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

main thread vs worker threads

Thread states

Synchronization
Method level
class Methodlevel {
//shared among threads

Block level

Class Blocklevel {
//shared among threads
SharedResourse x,y;
//dummy objects for locking
Object xlock = new Object(), ylock = new Object();
public void method1() {
synchronized(xlock) {

SharedResourse x,y;

//access x here sequentially (thread safe)

public synchronized void method1() {


//multiple threads cannot access
concurrently

}
x,y

//do something here, but dont access shared resourses


because the code here is not thread safe
synchronized(xlock) {

synchronized(ylock) {

public synchronized void method2() {

// sequential (thread safe) access to x and y


}

//multiple threads cannot access


concurrently
}
public void method3() {

}
x,y

//do something here, but dont access shared resourses


because the code here is not thread safe

} // end of method1()
} // end of class

Thread class
The class java.lang.Thread has the following constructors:

public
public
public
public

Thread();
Thread(String threadName);
Thread(Runnable target);
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 class
The 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

Methods of java.lang.Thread class


Method

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 readyto-run state.

Multi tasking
On 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 execution


Each 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

Concurrency vs Parallelism
Concurrent 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.

You might also like