Sunteți pe pagina 1din 19

Java Threads

Ahmed Adel
Omar Ismail
?What is a Thread
Individual and separate unit of execution that •
is part of a process
multiple threads can work together to accomplish –
a common goal
Video Game example •
one thread for graphics –
one thread for user interaction –
one thread for networking –
Thread Support in Java
Few programming languages directly support threading
Although many have add-on thread support
Add on thread support is often quite cumbersome to use

The Java Virtual machine has its own runtime threads


Used for garbage collection

Threads are represented by a Thread class


A thread object maintains the state of the thread
It provides control methods such as interrupt, start, sleep, yield, wait

When an application executes, the main method is


.executed by a single thread
.If the application requires more threads, the application must create them
A single threaded program
class ABC
{
.…
)..(public void main begin

{
… body

..
end
}
}

4
A Multithreaded Program

Main Thread

start
start start

Thread A Thread B Thread C

Threads may switch or exchange data/results


5
...Threading Mechanisms
Create a class that extends the Thread class •
Create a class that implements the Runnable •
interface

Thread Runnable Thread

MyThread MyClass

)objects are threads( )objects with run() body(

]a[ ]b[

6
1st method: Extending Thread class
Create a class by extending Thread class and override run() •
:method
class MyThread extends Thread
{
)(public void run
{
thread body of execution //
}
}
:Create a thread •
;)(MyThread thr1 = new MyThread
:Start Execution of threads •
;)(thr1.start
:Create and Execute •
;)(new MyThread().start

7
An example
{ class MyThread extends Thread
{ )(public void run
;System.out.println(" this thread is running ... ")
}
}

{ class ThreadEx1
{ public static void main(String [] args )
;)(MyThread t = new MyThread
;)(t.start
}
}

8
2nd method: Threads by implementing
Runnable interface
Create a class that implements the interface Runnable and override •
:run() method
class MyThread implements Runnable
{
.....
)(public void run
{
thread body of execution //
}
}
:Creating Object •
;)(MyThread myObject = new MyThread
:Creating Thread Object •
;Thread thr1 = new Thread( myObject )
:Start Execution •
;)(thr1.start

9
An example
{ class MyThread implements Runnable
{ )(public void run
;System.out.println(" this thread is running ... ")
}
}

{ class ThreadEx2
{ public static void main(String [] args )
;Thread t = new Thread(new MyThread())
;)(t.start
}
}

10
Shared Resources
If one thread tries to read the data and other thread •
tries to update the same data, it leads to inconsistent
.state
This can be prevented by synchronising access to the •
.data
:Use “Synchronized” method •
)(public synchronized void update –
{–
… •
}–

11
Synchronization
• // A Class used to send a message
• class Sender
• {
•     public void send(String msg)
•     {
•         System.out.println("Sending\t"  + msg );
•         try
•         {
•             Thread.sleep(1000);
•         }
•         catch (Exception e)
•         {
•             System.out.println("Thread  interrupted.");
•         }
•         System.out.println("\n" + msg + "Sent");
•     }
• }

12
…Cont
• // Class for send a message using Threads
• class ThreadedSend extends Thread
• {
•     private String msg;
•     Sender  sender;
•   
•     // Recieves a message object and a string
•     // message to be sent
•     ThreadedSend(String m,  Sender obj)
•     {
•         msg = m;
•         sender = obj;
•     }
…Cont
•   public void run()
•     {
•         // Only one thread can send a message
•         // at a time.
•         synchronized(sender)
•         {
•             // synchronizing the snd object
•             sender.send(msg);
•         }
•     }
• }
• class SyncDemo


{
…Cont
    public static void main(String args[])
•     {
•         Sender snd = new Sender();
•         ThreadedSend S1 =
•             new ThreadedSend( " Hi " , snd );
•         ThreadedSend S2 =
•             new ThreadedSend( " Bye " , snd );
•   
•         // Start two threads of ThreadedSend type
•         S1.start();
•         S2.start();
•   
•         // wait for threads to end
•         try
•         {
•             S1.join();
•             S2.join();
•         }
•         catch(Exception e)
•         {
•             System.out.println("Interrupted");
•         }
•     }
• }
Block Synchronization
public class SavingsAccount
{
;private float balance

public void withdraw(float anAmount)


{
if (anAmount<0.0)
;throw new IllegalArgumentException("Withdraw amount negative")
synchronized(this)
{
if (anAmount<=balance)
;balance = balance - anAmount
}
}

public void deposit(float anAmount)


{
if (anAmount<0.0)
;throw new IllegalArgumentException("Deposit amount negative")
synchronized(this)
{
;balance = balance + anAmount
}
}
Thread States
Threads can be in one of four states
Created, Running, Blocked, and Dead

:A thread's state changes based on


Control methods such as start, sleep, yield, wait, notify
Termination of the run method

)(notify
)(Thread )(start
Created Runnable Blocked
)(sleep
)(wait

run() method terminates

Dead
Controlling Java Threads
start(): begins a thread running._ •
wait() and notify(): for synchronization •
stop(): kills a specific thread (deprecated)._ •
suspend() and resume(): deprecated._ •
join(): wait for specific thread to finish._ •
setPriority(): 0 to 10 (MIN_PRIORITY to._ •
MAX_PRIORITY); 5 is default (NORM_PRIORITY)
Java Thread Scheduling
highest priority thread runs •
if more than one, arbitrary –
yield(): current thread gives up processor so •
another of equal priority can run
if none of equal priority, it runs again –
sleep(msec): stop executing for set time •
lower priority thread can run –

S-ar putea să vă placă și