Concurrent Programming in Java: Mrs. S.S.Jamsandekar Department of Computer Science Shivaji University

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 27

Concurrent Programming in Java

Mrs. S.S.Jamsandekar
Department of Computer Science
Shivaji University
JAVA Threads
 Concurrent Programming in Java
 Two basic units of execution
 processes
Threads
 Processes
 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.
 Processes are often seen as synonymous with
programs or applications.
 Java virtual machine run as a single process.
 Java application can create additional processes using a
ProcessBuilder object .
JAVA Threads
 Threads
 Threads are sometimes called lightweight processes
 Threads also provide an execution environment
 Creating a new thread requires fewer resources than
creating a new process.
 Thread cannot exist on its own (threads exist within a
process )
 Threads share the process's resources, including
memory and open files
 A thread is an independent path of execution within a
program. (collection of statements that execute in a
specific order)
 Every application has at least one thread — or
several( main Thread)
JAVA Threads
 Multithreaded execution is an essential feature of the
Java platform
 Multithreading refers to two or more tasks executing
concurrently within a single program..
 A Java program can have many threads, and these
threads can run concurrently, either asynchronously
or synchronously.

Multithreading has several advantages over Multiprocessing


 Threads are lightweight compared to processes
 Threads share the same address space and therefore can share
both data and code
 Context switching between threads is usually less expensive
than between processes
 Cost of thread intercommunication is relatively low that that of
process intercommunication
 Threads allow different tasks to be performed concurrently.
Thread Life Cycle Model
Thread Life Cycle Model
Thread Life Cycle Model
 New state – After the creations of Thread instance the thread is in
this state but before the start() method invocation. At this point, the
thread is considered not alive.
     
 Runnable (Ready-to-run) state – A thread start its life from
Runnable state. A thread first enters runnable state after the
invoking of start() method but a thread can return to this state after
either running, waiting, sleeping or coming back from blocked state
also. On this state a thread is waiting for a turn on the processor. 
     
 Running state – A thread is in running state that means the thread
is currently executing. There are several ways to enter in Runnable
state but there is only one way to enter in Running state: the
scheduler select a thread from runnable pool.
     
 Dead state – A thread can be considered dead when its run()
method completes. If any thread comes on this state that means it
cannot ever run again.
 Blocked - A thread can enter in this state because of waiting the
resources that are hold by another thread
Java Threads

Thread Creation
 There are two ways to create thread in
java;
– Implement the Runnable interface
(java.lang.Runnable)
– By Extending the Thread class
(java.lang.Thread)
Thread Class
public class Thread
extends Object
implements Runnable

 Every thread has a priority.


 Threads with higher priority are executed in preference
to threads with lower priority
 A new Thread inheriting the priority of the thread that
created it
 Java thread can have any priority between 1 and 10
Thread Class
Constructors:
Thread()
          Allocates a new Thread object.
Thread ( Runnable target )
          Allocates a new Thread object.
Thread (Runnable target, String name)
          Allocates a new Thread object.
Thread (String name)
          Allocates a new Thread object.
Thread (ThreadGroup group, Runnable target)
          Allocates a new Thread object.
Thread (ThreadGroup group, Runnable target, String name)
          Allocates a new Thread object so that it has target as its run
object, has the specified name as its name, and belongs to the thread
group referred to by group.
Thread (ThreadGroup group, Runnable target, String name, long stackSize)
          Allocates a new Thread object so that it has target as its run
object, has the specified name as its name, belongs to the thread
group referred to by group, and has the specified stack size.
Thread (ThreadGroup group, String name)
          Allocates a new Thread object.
Thread Class: Methods
Return type Method Description
static void            dumpStack() Prints a stack trace of the current thread
to the standard error stream.
Long            getId() Returns the identifier of this Thread.
String getName()  Returns this thread's name.
Static Thread currentThread() Returns a reference to the currently
executing thread object.
Int getPriority() Returns this thread's priority.

Thread.State getState() Returns the state of this thread.

static boolean           holdsLock(Object obj) Returns true if and only if the current


thread holds the monitor lock on the
specified object.
void          interrupt()  Interrupts this thread.

Boolean isAlive() Tests if this thread is alive.


void join() The current thread invokes this method on
second thread, causing the current thread to
block until the second thread terminates .
void  join (long millis)  Waits for the specified milliseconds to pass

 void run() If this thread was constructed using a separate


           Runnable run object, then that Runnable object's
run method is called; otherwise, this method
does nothing and returns.
void setName (String name) Changes the name of this thread to be equal to
            the argument name.
          
void setPriority (int newPriority) Changes the priority of this thread.

static void Sleep (long millis)  Causes the currently executing thread to


sleep (temporarily cease execution) for the
         . specified number of milliseconds,
void start() Causes this thread to begin execution; the
Java Virtual Machine calls the run method of
           this thread.
static void yield() Causes the currently executing thread object
to temporarily pause and allow other threads to
           execute.
Creating Thread : Thread class
class XThread extends Thread{

XThread(){

XThread(String threadName){
super(threadName); // Initialize thread.
System.out.println(this);
start();
}

public void run(){


//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}
public class ThreadExample
{
public static void main(String[] args)
{
Thread thread1 = new Thread(new XThread(),"thread1");
Thread thread2 = new Thread(new XThread(),"thread2");

// The below 2 threads are assigned default names


Thread thread3 = new XThread();
Thread thread4 = new XThread();

Thread thread5 = new XThread("thread5");


//Start the threads
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try{
//The sleep() method is invoked on the main thread to cause a one second delay.
Thread.currentThread().sleep(1000);
}catch(InterruptedException e){}

//Display info about the main thread


System.out.println(Thread.currentThread());
}
}
Creating Thread : implement Runnable
class RunnableThread implements Runnable
{
Thread runner;
public RunnableThread()
{}
public RunnableThread(String threadName)
{
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}
public void run()
{
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}
public class RunnableExample
{
public static void main(String[] args)
{
Thread thread1 = new Thread(new RunnableThread(), "thread1");
Thread thread2 = new Thread(new RunnableThread(), "thread2");
RunnableThread thread3 = new RunnableThread("thread3");
//Start the threads
thread1.start();
thread2.start();
try { //delay for one second
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e)
{ }
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}

This approach of creating a thread by implementing the Runnable Interface must be


used whenever the class being used to instantiate the thread object is required to
extend some other class.
Yeild() method
class GuessNumber extends Thread
{
private int number;

public GuessNumber( int number)


{
this.number=number;
}
public void run()
{
int counter = 0;
int guess= 0;
do
{ Thread.yield();
guess = (int)(Math.random()*100+1);
System.out.println(this.getName()+ "guesses"+guess);
counter++;
}
while(guess!=number);
System.out.println(" correct!" + this.getName() + "in" + counter + "guesses" );
}
}
public class yieldDemo
{
public static void main(String [] args)
{
System.out.println(" pick a number between 1 and 100 ...");
Thread player1= new GuessNumber(45);
Thread player2= new GuessNumber(45);
Thread player3= new GuessNumber(45);

player3.setPriority(Thread.MAX_PRIORITY);

player3.start();
player1.start();
player2.start();

}
}
class GuessNumber1 extends Thread
Join() Method
{
private int number;
public GuessNumber1( int number)
{
this.number=number; }
public void run()
{
int counter = 0;
int guess= 0;
do
{
guess = (int)(Math.random()*100+1);
System.out.println(this.getName()+ "guesses"+guess);
counter++; }
while(guess!=number);
System.out.println(" correct!" + this.getName() + "in" + counter + "guesses" );
} }

class DisplayMessage implements Runnable


{
private String msg;

public DisplayMessage(String message)


{
this.msg=message; }
public void run()
{
while(true)
{
System.out.println(msg); } } }
public class JoinDemo
{
public static void main(String args[])
{
Runnable hello = new DisplayMessage("hello");
Thread thread1 = new Thread(hello);

thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread.....");
thread1.start();

Runnable bye = new DisplayMessage("Goodbye");


Thread thread2 = new Thread(bye);
thread2.setDaemon(true);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setName("Goodbye");
System.out.println("Starting Goodbye thread.....");
thread2.start();

System.out.println("starting thread 3......");


Thread thread3= new GuessNumber1(25);
thread3.setName(" Guess thread 1");
thread3.start();
try
{ thread3.join();
}
catch(InterruptedException e)
{}
System.out.println("starting thread 4......");
Thread thread4= new GuessNumber1(75);
thread4.setName(" Guess thread 2");
thread4.start();
System.out.println("main() is ending ......");
}
}
synchronization
 The Java programming language provides two basic
synchronization idioms:
 synchronized methods
 synchronized statements
 How to make a method synchronized?
 simply add the synchronized keyword to its declaration:
 Synchronized keyword in java creates a block of code
referred to as a critical section.
 Every java object with critical section of code gets a lock
associated with it
public class SynchronizedCounter
{
private int c = 0;
public synchronized void increment()
{
c++;
}
public synchronized void decrement()
{
c--;
}
public synchronized int value()
{
return c;
}
}
• If count is an instance of SynchronizedCounter, then making these methods
synchronized has two effects:
• First, it is not possible for two invocations of synchronized methods on the same
object to interleave. When one thread is executing a synchronized method for an
object, all other threads that invoke synchronized methods for the same object block
(suspend execution) until the first thread is done with the object.
• Second, when a synchronized method exits, it automatically establishes a happens-
before relationship with any subsequent invocation of a synchronized method for the
same object. This guarantees that changes to the state of the object are visible to all
threads.
wait ()and notify ()methods
Java.lang.Object class (Root class)
 wait()
 Notify()
 These methods allow threads to communicate with each
other.
( used in producer consumer problem)
Return type Method Description

final void            wait() Causes the current thread to wait


indefinitely on this Object for notify() or
notifyAll()

final void                   wait(long timeout) Causes the current thread to wait on


this Object. Thread continues when
either another thread invokes notify() or
notifyAll(), or when specified time is
elapsed.
final void      notify()  Wakes up one thread that is waiting on
this Object.

final void      notifyAll() Similar to notify(), except that all waiting


threads are awaken instead of just one.

* All four methods can be called only from within a synchronized method
class Q
{
int n;
boolean valueSet = false;

synchronized int get() {


if (!valueSet)
try {
wait();
} catch(InterruptedException e){
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}

synchronized void put(int n) {


if(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}

}
class Producer implements Runnable
{
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}} }

class Consumer implements Runnable


{
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}}}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Questions ?

You might also like