Thursday, 20 November 2014

Java Concurrency - Processes and Threads

Process


Process is self contained environment meaning it got its own basic resources importantly own memory space. For communication between processes we need interprocess communication (sockets, pipes etc) provide by operating system.

Most implementations of JMV runs as single process. Java application can create multiple or additional processes by using java.lang.ProcessBuilder object.

Threads


Threads exists within process and every process has at least one thread. Thread share process's resources that includes memory, open files etc; hence creating new thread requires few resources. Threads sometime called as lightweight process. Each thread is associated with instance of class Thread.

Their are two strategies of  Thread
1. Manual - Control thread creation and management by instantiating Thread each time application want to perform asynchronous task
2. Executors - Separate thread management from application by passing tasks to Executor.

Defining and starting a thread

1. Provide Runnable object - Implement Runnable interface which defines a single method run()
2. Subclass Thread class - Extends Thread class.

It will be wise to implement Runnable interface instated of extending Thread class. Coz we can extend other classes if required if we implement Runnable interface but we can not if we extend Thread class.

Thread.sleep(long miliSeconds) causes current thread to suspend execution for specific time. Sleep timings are not guarantied to be precise as it depends on facilities provided by underlaying operating system.

Good example of basic thread working

Ref: Java SE tutorials

No comments:

Post a Comment