Sei sulla pagina 1di 43

Multithreaded Programming

Java provides built-in support for multithreaded


programming. A multithreaded program contains two or
more parts that can run concurrently. Each part of such a
program is called a thread and each thread defines a
separate path of execution. Thus multithreading is a
specialized form of multitasking.
Two types of multitasking:
Process based
Thread based.

Multithreaded Programming

A process is a program that is executing. Thus processbased multitasking is the feature that allows your
computer to run two or more programs concurrently.
Example process based multitasking enables you to run
the java compiler at the same time that you are using a
text editor. In process based multitasking, a program is
the smallest unit of code.

Process versus thread based


multitasking

In a thread-based multitasking ,the thread is the smallest


unit of dispatchable code. This means that a single
program can perform two or more tasks simultaneously.
Multitasking threads requires less overhead than
multitasking processes. Processes are heavyweight tasks
that requires their own separate address space.
Interprocess communication is expensive and limited.
Context switching from one process to another is also
costly .

Process versus thread based


multitasking

Threads are lightweight. They share same address space.


Inter thread communication is inexpensive, and context
switching from one thread to the next is low cost.
Process-based multitasking is not under the control of
Java but multithreaded multitasking is in control.

Java Thread Model

Single threaded systems use an approach called an event loop


with polling. In this model a single thread of control runs in an
infinite loop, polling a single event queue to decide what to do
next. Sometimes this method wastes CPU time or entire
program stops running.
Javas multithreading is that the main loop/polling mechanism
is eliminated. One thread can pause without stopping other
parts of your program. When thread blocks Java program, only
the single thread that is blocked pauses. All other threads
continue to run.

Thread states

Threads exist in several states.

Running
Ready
Suspended
Resumed
Blocked
terminated

synchronization

Multithreading introduces an asynchronous behavior so you must


prevent one thread from writing data while another thread is in the
middle of reading it.
Java implements interprocess synchronization called monitor.
Monitor a very small box that can hold only one thread. Once a
thread enters a monitor, all other threads must wait until that thread
exits the monitor.
There is no class Monitor ,instead each object has its own implicit
monitor that is automatically entered when one of the objects
synchronized methods is called. Once a thread is inside a
synchronized method, no other thread can call any other
synchronized method on the same object.

Messaging

Java provides a clean, low cost way for two or more threads to
communicate with each other via calls to predefined methods
that all object have.
Javas messaging system allows a thread to enter a
synchronized method on an object, and then wait there until
some other thread explicitly notifies it to come out.

The Thread Class and the Runnable


Interface

Javas multithreading system is built upon the thread class, its methods, and its
companion interface, Runnable.
To create a new thread, your program will either extend Thread or implement the
Runnable interface.
The thread class defines several methods that help to manage threads.
Method

Meaning

getName

Obtain a threads name.

getPriority

Obtain a threads 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.

Extending Thread class

We can make our class runnable as a thread by extending the


class java.lang.Thread. This gives us access to all the thread
methods directly.
Steps
Declare the class as extending the Thread class
Implement the run() method that is responsible for
executing the sequence of code that the thread will execute.
Create a thread object and call the start() method to initiate
the thread execution.

Declaring the class


The thread class can be extended as follows:
Class Mythread extends Thread
{
----------------}

Implement the run() method


The run() method has been inherited by the class Thread. We have to
override this method in order to implement the code to be executed by our
thread.
public void run()
{
------------------}

Starting new thread


To actually create and run an instance of our thread class.
Mythread athread= new Mythread();// creates object
athread.start();

class A extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(From A: i= +i);
}
System.out.println(Exit form A);
}
}

Class B extends Thread


{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println(From B: j= +j);
}
System.out.println(Exit form B);
}
}

Class C extends Thread


{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println(From C: k= + k);
}
System.out.println(Exit form C);
}
}

class Threadtest
{
public static void main(String args[])
{
new A() .start();
new B().start();
new C().start();
}
}

class A extends Thread


{
public void run()
{
for(int i=1;i<5;i++)
{if(i==1)yield();
System.out.println("\tFrom Thread A: i=" +i);
}
System.out.println("Exit from A");
}
}

class B extends Thread


{
public void run()
{
for(int j=1;j<5;j++)
{
System.out.println("\tFrom Thread A: i=" +j);
if(j==3)stop();
}
System.out.println("Exit from B");
}
}

class C extends Thread


{
public void run()
{
for(int k=1;k<5;k++)
{
System.out.println("\t From Thread C: k=" +k);
if(k==1)
try
{
sleep(1000);
}
catch(Exception e)
{}
}
System.out.println("Exit from C");
} }

class ThreadMethods
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
System.out.println("start thread A");
threadA.start();
System.out.println("start thread B");
threadB.start();
System.out.println("Start thread C");
threadC.start();
System.out.println("End of main thread");
}

class A extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(From A: i= +i);
}
System.out.println(Exit form A);
}
}

Class B extends Thread


{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println(From B: j= +j);
}
System.out.println(Exit form B);
}
}

class Threadtest
{
public static void main(String args[])
{
A threadA=new A();
B threadB= new B();
threadB.setPriority(Thread.MAX_PRIORITY);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println(start thread A);
threadA.start();
System.out.println(start thread B);
threadB.start();
}

Using isAlive() and join()

isAlive():
final boolean isAlive()
The isAlive() method returns true if the thread upon which it is
called is still running. It returns false otherwise.
join(): (wait for thread to terminate)
final void join() throws InterruptedException
This method waits until the thread on which it is called
terminates.

Example 3
class A extends Thread
{
public void run()
{ for(int i=1;i<5;i++){
System.out.println("\tFrom Thread A: i=" +i); }
System.out.println("Exit from A");
}
void call()
{ start(); } }

Example 3
class B extends Thread
{
public void run()
{
for(int j=1;j<5;j++)
{
System.out.println("\tFrom Thread B: j=" +j);
}
System.out.println("Exit from B");
}
}

Example 3
class ThreadMethods1
{
public static void main(String args[])
{ A threadA=new A();
B threadB=new B();
System.out.println("start thread A");
threadA.call();
System.out.println("start thread B");
threadB.start();
System.out.println("End of main thread");
}
}

Example 3(Using Join()


class ThreadMethods1
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
System.out.println("start thread A");
threadA.call();
System.out.println("start thread B");
threadB.start();
try{
threadA.join();
threadB.join();
}
catch(InterruptedException e) { System. out.println("Interrupted);}
}
System.out.println("End of main thread");
}

Implementing Runnable

Steps:
1. Declare the class as implementing the Runnable
interface.
2. Implement the run() method.
3. Create a thread by defining an object that is
instantiated from this runnable class as the target of
the thread.
4. Call the threads start() method to run the method.

Example1(Runnable interface)
class runnableex implements Runnable
{
public String t;
runnableex(String s){t=s;}
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(t+ "Thread " + i);
}
System.out.println("End of thread" + t);
}
}

class runnable1{
public static void main(String args[])
{
runnableex ob1=new runnableex("FIRST");
Thread thread1=new Thread(ob1);
runnableex ob2=new runnableex("SECOND");
Thread thread2=new Thread(ob2);
System.out.println("thread1");
thread1.start();
System.out.println("thread2");
thread2.start();
System.out.println("End of main");
}
}

Example1(Runnable interface)
class runnableex implements Runnable //step1
{
public String t;
runnableex(String s){t=s;}
public void run()
//step2
{
for(int i=1;i<=5;i++)
{
System.out.println(t+ "Thread " + i);
}
System.out.println("End of thread" + t);
}
}

class runnable1{
public static void main(String args[])
{
runnableex ob1=new runnableex("FIRST");
Thread thread1=new Thread(ob1); //step3
runnableex ob2=new runnableex("SECOND");
Thread thread2=new Thread(ob2);
System.out.println("thread1");
thread1.start();
//step4
System.out.println("thread2");
thread2.start();
System.out.println("End of main");
}
}

Example2(using Runnable
interface)
class runnableex2 implements Runnable
{
public String t;
runnableex2(String s){t=s;}
public void run()
{
for(int i=1;i<=5;i++)
{ System.out.println(t+ "Thread " + i); }
System.out.println("End of thread" + t);
}
void get1(Thread G)
{ G.start(); }
}

Example2(using Runnable
interface)
class runnable2{
public static void main(String args[])
{
runnableex2 ob1=new runnableex2("FIRST");
Thread thread1=new Thread(ob1);
runnableex2 ob2=new runnableex2("SECOND");
Thread thread2=new Thread(ob2);
System.out.println("thread1");
ob1.get1(thread1);
System.out.println("thread2");
ob2.get1(thread2);
System.out.println("End of main");
}

Synchronization

When two or more threads needs access to a shared resource, they


need some way to ensure that the resource will be used by only one
thread at a time. The process by which this is achieved is called
synchronization.
Key to synchronization is the concept of the monitor (semaphore). A
monitor is an object that is used as a mutually exclusive lock or
mutex. Only one thread can own a monitor at a given time.
When thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor. These other
threads are said to be waiting for the monitor.

The synchronized statement


Synchronized method_name()
{
------------------------------}
OR
Synchronized(object){
//statement to be synchronized
}

Example:
class callme{
void call(String msg){
System.out.print([ +msg);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println(interrupted);
}
System.out.println(]);
}
}

class caller implements Runnable{


String msg;
Callme target;
thread t;
public caller(callme targ,String s){
target=targ;
msg=s;
t=new Thread(this);
t.start();
}

public void run()


{
synchronized(target){
target.call(msg);
}
}}
class synch1{
public static void main(String args[]){
callme target=new callme();
caller ob1=new Caller(target,hello);
caller ob2=new Caller(target,synchronized);
caller ob3=new Caller(target,world);
}
}

Using synchronized keyword


Class callme{
Synchronized void call(string msg){

}
This prevents other threads from entering call()
while another thread is using it.

Deadlock
Thread A
Synchronized method2()
{
Synchronized method1()
{
.
.
}
}
Thread B
Synchronized method1()
{
Synchronized method2()
{

Potrebbero piacerti anche