Lect06 Part1 Week4
Lect06 Part1 Week4
Dr Walid M. Aly
Lecture6
Threads
1
12:06
Introduction
3
12:07
Thread ecology started
in aby java
javafrom
program
main(String[])
started by main
thread
started by B
thread
lifetime of C
thread
Cheng-Chia
Chen
Portability Tip
12:07
Example on concurrent threads execution
void m1(){ void m2(){ void m3(){
while (true) while (true) while (true) m1();
{ { { m2();
print (‘a’); print (‘b’); print (‘c’); m3();
} } }
Normal execution with only one thread Execution with multiple threads
a a
a a
a b
a c
a c
a a
a ..
.. ..
6
12:07
Threads states.
• A thread can be ready to run.
• A thread can be running.
• A thread can be blocked when waiting for a resource.
• The CPU divides its time between threads according to a schedule set by the
operating system.
• A thread may never get a chance to run if there is always a higher-priority
thread running or a same-priority thread that never yields. This situation is
known as contention or starvation.
• A Thread can leave the running state and go to the ready state by calling the
yield() method defined in class Thread.
7
12:07
Example on thread blocking
The thread executing the code will be blocked at line 2 until there are data to read.
java.io.DataInputStream
public final int readInt()
Reads four input bytes and returns an int Value
This method blocks until input data is available
8
12:07
Threads created by JVM
main thread
When a Java program starts up, one thread begins
running immediately.
This is the main thread of your program and the one
that is executed when your program begins.
The main thread is the thread from which other “child”
threads will emerge.
For example : The main thread of a server will create a
thread to deal with each client connection
9
12:07
java.lang.Thread
Constructors
Thread()
Thread(String name)
Thread(Runnable target)
Thread(Runnable target, String name)
Methods
public final String getName()
public void start() // Causes this thread to begin execution; the Java
Virtual Machine calls the run method of this thread.
public 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.
public final void join() throws InterruptedException
// wait for a thread to die
public final boolean isAlive()
java.lang.Runnable
10
12:07 public void run() //execute the thread
Example 1 : Dealing with the main Thread
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
…..
}}
java.lang.Thread
public static Thread currentThread()
Returns a reference to the currently executing thread object
public String toString() Returns a string representation of this thread, including
the thread's name, priority, and thread group.
public static void sleep(long millis) throws InterruptedException Causes the11
currently executing thread to sleep (temporarily cease execution) for the
How to create Threads?
• extend java.lang.Thread and override public void run()
or
• implement the java.lang.Runnable interface by implementing
public void run().
class A extends Thread { class A implements Runnable {
public void run() public void run()
{ {
// //
} }
} }
class ThreadDemo {
class ThreadDemo {
public static void main(String args[]) {
public static void main(String args[]) {
A a=new A();
A a=new A( );
Thread t = new Thread(a);
a.start(); // Start the thread and execute run
t.start(); /// Start the thread and execute run
}
}
}
}
Calling start () automatically invokes run() :if you can call run() directly, instead of calling start()
no new thread is created and program executed within the same thread (no multitreading)12
Creating threads by extending Thread
public class Client extends Thread {
String name;
public Client(String name){
this.name=name;}
public void run(){
System.out.println("Serving client.... :"+ name);
try{
Thread.sleep(1000);}
catch (Exception ex){}
System.out.println("End Serving client :"+ name);
} Nondeterministic
}}} output
class ClientServer {
public static void main(String args[]) {
Client client1=new Client("Ahmed ");
Client client2=new Client("Mohamed ");
Client client3=new Client("Tarek");
client1.start(); // Start the thread
client2.start(); // Start the thread
client3.start(); // Start the thread
13
}} 12:07