PROCESS
1) A
program in execution is often referred as process. A thread is a subset(part)
of the process.
2) A
process consists of multiple threads. A thread is a smallest part of the
process that can execute concurrently with other parts(threads) of the process.
3) A
process is sometime referred as task. A thread is often referred as lightweight
process.
4) A
process has its own address space. A thread uses the process’s address space
and share it with the other threads of that process.
5) PER PROCESS ITEMS VS. PER THREAD ITEMS
Per process items Per
thread items
Global variables Registers
Open files Stack
Child processes State
Pending alarms
Signals and signal
handlers
Accounting
information
6) A
thread can communicate with other thread (of the same process) directly by
using methods like wait(), notify(), notifyAll(). A process can communicate
with other process by using inter-process communication.
7) New
threads are easily created. However the creation of new processes require
duplication of the parent process.
8)
Threads have control over the other threads of the same process. A process does
not have control over the sibling process, it has control over its child
processes only.
A process
is a collection of code, memory, data and other resources. A thread is a
sequence of code that is executed within the scope of the process.
A thread
is the basic unit to which the operating system allocates processor time. One
or more threads run in the context of the process.
A
process, in the simplest terms, is an executing program. An application
consists of one or more processes.
EXAMPLE
PROCESS 1
[(Thread 1), (Thread 2), (Thread 3)]
PROCESS 2
[(Thread 1), (Thread 2), (Thread 3)]
PROCESS 3
[(Thread 1), (Thread 2), (Thread 3)]
NOTE:
- To list all the process in command Prompt: tasklist
- Output: Image name, Pid, Session Name, Session #, Mem Usage
- To kill a process: tskill process_name Eg. tskill notepad
- To list all the process in Windows machine: tasklist /svc
- Output: Image Name, Pid, Services
- To filter any process: tasklist|findstr "firefox.exe"
- To view active connections with process id: netstat -aon | more
- Then kill a process with process id: taskkill /F /PID 28344
- To view system information: systeminfo
- Java Execute a command to kill a process: Runtime.getRuntime().exec("TASKKILL /F /IM spotify.exe");
The Process Class
The
Process is an abstract class defined in the java.lang package that encapsulates
the runtime information of a program in execution. The exec method invoked by
the Runtime instance returns a reference to this class instance.
Some of the common methods defined in this class are:
- Exits code returned from the process executed
- int exitValue()
- Reads/writes output, error, and input streams to and from the process.
- InputStream getErrorStream()
- InputStream getInputStream()
- OutputStream getOutputStream()
- Checks to see if the invoking process is still running.
- Boolean isAlive()
- Waits for the invoking process to end. The integer value returned by the method is the exit code by the process. In another overloaded method, we can specify the wait time. This method returns true if the process has terminated and false if timeout has occurred.
- int waitFor()
- Boolean waitFor(long timeOut, TimeUnit unit)
- These two methods are used to kill or terminate the process. One, the second, just does it forcibly.
- void destroy()
- Process destroyForcibly()
NOTE
Notepad is a text editor from windows
operating system. We use notepad for writing text files.
We can open a new notepad using java code.
By using the concept of running another
application by Runtime class in java.
By creating object of runtime and
calling exec() method by passing application name.
PROCESS EXAMPLE: TO EXECUTE ANY
PROCESS/APPLICATION
import
java.io.IOException;
public
class notepad {
public static void main(String[] args) {
Runtime rt =
Runtime.getRuntime();
try {
rt.exec("notepad");
}
catch (IOException ex) {
System.out.println(ex);
}
}
}
PROCESS
EXAMPLE 2: TO OPEN AND CLOSE NOTEPAD APPLICATION
import java.io.IOException;
public class notepad {
public static void main(String[] args) throws
InterruptedException, IOException {
Runtime runTime = Runtime.getRuntime();
System.out.println("Opening
notepad");
Process process =
runTime.exec("notepad");
try {
Thread.sleep(2000);
process.destroy();
System.out.println("Closing
notepad");
}
catch
(Exception ex) {
System.out.println(ex);
}
}
}
PROCESS
EXAMPLE 3: TO OPEN ANY EXISTING NOTEPAD APPLICAITON
import java.io.IOException;
public class notepad {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
try {
rt.exec("C:\\Windows\\System32\\notepad.exe
E:\\Samplenotepad.txt");
}
catch
(IOException ex) {
System.out.println(ex);
} } }
PROCESS
EXAMPLE 4: TO LIST ALL THE PROCESS
import java.io.*;
public class Tolist {
public static void main(String[] args)throws
IOException
{
Runtime runtime = Runtime.getRuntime();
String cmds[] = {"cmd", "/c", "tasklist"};
Process proc = runtime.exec(cmds);
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new
InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
}
}
MULTITASKING
Multitasking
:
Multitasking is an
operation in which multiple tasks are performed simultaneously.
Multitasking is used to utilize CPU’s idle time. Multitasking can be of two
types. One is process-based and another one is thread-based.
1)
Process-based multitasking Or Multiprocessing :
In process-based multitasking
or multiprocessing, Multiple processes are executed simultaneously. You are all
familiar with process-based multitasking. Because of this feature only, your
computer runs two or more programs simultaneously. For example, You can play a
video file and print a text file simultaneously in your computer.
2)Thread-based
Multitasking Or Multithreading:
In thread-based multitasking or
multithreading, multiple threads in a process are executed
simultaneously. For example, MS word can print a document using
background thread, at the same another thread can accept the user input so that
user can create a new document.
SINGLE THREAD: JAVA PROGRAM
import java.io.*;
public class Singlethread
{
//Main Thread
public static void main(String[] args)
{
for (int i = 0; i <= 10; i++)
{
System.out.println("From Main Thread");
}
}
}
MULTITHREADED
PROGRAMMING:
//Defining
first thread with task
//The
task of this thread is to print the numbers from 0 to 1000 times
class
Thread1 extends Thread
{
@Override
public void run()
{
for(int i = 0; i <= 10; i++)
{
System.out.println(i);
}
}
}
//Defining
second thread with task
//The
task of this thread is to print the numbers from 1001 to 2000
class
Thread2 extends Thread
{
@Override
public void run()
{
for(int i = 11; i<= 20; i++)
{
System.out.println(i);
}
}
}
public
class Multitask
{
//Main Thread
public static void main(String[] args)
{
//Creating first thread
Thread1 t1 = new Thread1();
t1.start();
//Creating second thread
Thread2 t2 = new Thread2();
t2.start();
}
}
Multitasking: Ability to execute more than one task at the same time
is known as multitasking.
Multithreading: We already discussed about it. It is a process of executing multiple threads simultaneously. Multithreading is also known as Thread-based Multitasking.
Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are involved. On the other hand one CPU is involved in multitasking.
Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.
THREADS IN JAVA
A thread
is a:
• Facility to allow multiple activities
within a single process
• Referred as lightweight process
• A thread is a series of executed
statements
• Each thread has its own program
counter, stack and local variables
• A thread is a nested sequence of
method calls
• Its shares memory, files and
per-process state
Use
of Threads?
- To perform asynchronous or background processing
- Increases the responsiveness of GUI applications
- Take advantage of multiprocessor systems
- Simplify program logic when there are multiple independent entities
When
a thread is invoked:
When a thread is invoked, there will
be two paths of execution. One path will execute the thread and the other path
will follow the statement after the thread invocation. There will be a separate
stack and memory space for each thread.
Risk
Factor
- Proper co-ordination is required between threads accessing common variables [use of synchronized and volatile] for consistence view of data
- overuse of java threads can be hazardous to program’s performance and its maintainability.
Threads
in Java
Every java program creates at least
one thread [ main() thread ]. Additional threads are created through the Thread
constructor or by instantiating classes that extend the Thread class.
Threads are lightweight
sub-processes, they share the common memory space. In Multithreaded
environment, programs that are benefited from multithreading, utilize the
maximum CPU time so that the idle time can be kept to minimum.
Thread
creation in Java
Thread implementation in java
can be achieved in two ways:
- Extending the java.lang.Thread class
- Implementing the java.lang.Runnable Interface
Note: The Thread and Runnable are available in
the java.lang.* package
1)
By extending thread class
- The class should extend Java Thread class.
- The class should override the run() method.
- The functionality that is expected by the Thread to be executed is written in the run() method.
void start(): Creates a new
thread and makes it runnable.
void run(): The new thread begins its life inside this method.
void run(): The new thread begins its life inside this method.
NOTE: We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
Example:
public class MyThread extends Thread {
public void
run(){
System.out.println("thread is running...");
}
public static
void main(String[] args) {
MyThread obj
= new MyThread();
obj.start();
}
EXAMPLE
2:
class
Count extends Thread
{
Count()
{
super("my extending thread");
System.out.println("my thread
created" + this);
start();
}
public void run()
{
try
{
for (int i=0 ;i<5;i++)
{
System.out.println("Printing
the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread
interrupted");
}
System.out.println("My thread run is
over" );
}
}
class
MyThread
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.isAlive())
{
System.out.println("Main thread
will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread
interrupted");
}
System.out.println("Main thread's
run is over" );
}
}
2)
By Implementing Runnable interface
- The class should implement the Runnable interface
- The class should implement the run() method in the Runnable interface
- The functionality that is expected by the Thread to be executed is put in the run() method
Example:
public class MyThread implements
Runnable {
public void run(){
System.out.println("THREAD IS RUNNING USING RUNNABLE
INTERFACE.");
}
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
t.start();
} }
Example
2:
class
Count implements Runnable
{
Thread mythread ;
Count()
{
mythread = new Thread(this, "my
runnable thread");
System.out.println("my thread
created" + mythread);
mythread.start();
}
public void run()
{
try
{
for (int i=0 ;i<5;i++)
{
System.out.println("Printing the
count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread
interrupted");
}
System.out.println("mythread run is
over" );
}
}
class
MyThread
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.mythread.isAlive())
{
System.out.println("Main
thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread
interrupted");
}
System.out.println("Main thread run
is over" );
}
}
Ending
Thread
A Thread ends due to the
following reasons:
- The thread ends when it comes when the run() method finishes its execution.
- When the thread throws an Exception or Error that is not being caught in the program.
- Java program completes or ends.
- Another thread calls stop() methods.
THREAD STATES
·
NEW – A thread that has not yet
started is in this state.
·
RUNNABLE – A thread executing in the
Java virtual machine is in this state.
·
BLOCKED – A thread that is blocked
waiting for a monitor lock is in this state.
·
WAITING – A thread that is waiting
indefinitely for another thread to perform a particular action is in this
state.
·
TIMED_WAITING – A thread that is
waiting for another thread to perform an action for up to a specified waiting
time is in this state.
·
TERMINATED – A thread that has exited
is in this state.
·
A thread can be in only one state at
a given point in time..
Thread
States
- getName(): It is used for Obtaining a thread’s name
- getPriority(): Obtain a thread’s priority
- isAlive(): Determine if a thread is still running
- join(): Wait for a thread to terminate
- run(): Entry point for the thread
- sleep(): suspend a thread for a period of time
- start(): start a thread by calling its run() method
Methods of Thread
Method
|
Return Type
|
Description
|
currentThread(
)
|
Thread
|
Returns an
object reference to the thread in which it is invoked.
|
getName( )
|
String
|
Call the
name of the thread
|
start( )
|
void
|
Starts the
thread
|
run( )
|
void
|
This method
starts the execution of a thread
|
sleep( )
|
void
|
Suspends a
thread for a specified time
|
isAlive( )
|
boolean
|
This method
determines whethers a thread is running or not
|
activeCount(
)
|
int
|
This method
returns the number of active threads in a particular group and subgroups
|
interrupt(
)
|
void
|
This method
interrupt the threads on which it is invoked.
|
yield( )
|
void
|
This method
pauses the execution of current thread temporarily and allows other threads
to
|
class
thread implements Runnable
{
public void run()
{
// moving thread2 to timed waiting
state
try
{
Thread.sleep(1500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
try
{
Thread.sleep(1500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of
thread1 while it called join() method on thread2 -"+
Test.thread1.getState());
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public
class Test implements Runnable
{
public static Thread thread1;
public static Test obj;
public static void main(String[] args)
{
obj = new Test();
thread1 = new Thread(obj);
// thread1 created and is currently in
the NEW state.
System.out.println("State of thread1
after creating it - " + thread1.getState());
thread1.start();
// thread1 moved to Runnable state
System.out.println("State of
thread1 after calling .start() method on it - " +
thread1.getState());
}
public void run()
{
thread myThread = new thread();
Thread thread2 = new Thread(myThread);
// thread1 created and is currently in
the NEW state.
System.out.println("State of
thread2 after creating it - "+ thread2.getState());
thread2.start();
// thread2 moved to Runnable state
System.out.println("State of
thread2 after calling .start() method on it - " +
thread2.getState());
// moving thread1 to timed waiting
state
try
{
//moving thread2 to timed waiting
state
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of
thread2 after calling .sleep() method on it - "+
thread2.getState() );
try
// waiting for thread2 to die
thread2.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
System.out.println("State of
thread2 when it has finished it's execution - " +
thread2.getState());
}
}
.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.