Process
A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.
To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets. IPC is used not just for communication between processes on the same system, but processes on different systems.
Most implementations of the Java virtual machine run as a single process. A Java application can create additional processes using a ProcessBuilder object.
Thread
Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.
Threads exist within a process - every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.
Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread - or several, if you count "system" threads that do things like memory management and signal handling. But from the application programmers' point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads.
Preferred means of creating multthreaded application in J2SE5.0
Implement the Runnable interface and use build-in methods and classes to create Threads that execute the Runnables.
Runnables are executed by an object of a class that implements the Executor interface. An executor object typically creates and manages a group of threads called a thread pool.
ExecutorService's execute method creates a new Thread inside the ExecutorService to run the Runnable passed to it as an argument and transitions that Thread from the new state to the runnable state. Method execute returns immediately from each invocation - the program does not wait for each PrintTask to finish.
ExecutorService.shutdown() method will end each Thread in threadExecutor as soon as each finishes executing its Runnable.
If the program executed more than three Runnables, additional Threads would not be created, but rather an existing Thread would be reused when it completed the Runnable assigned to it.
The code in the method main executes in the main thread which is created by the JVM and executes the main method.
The code in the run method of PrintTask executes in the threads created by the ExecutorService. When method main terminates, the program itself continues running because there are still threads that are alive. The program will not terminate until its last thread completes execution.
ref
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment