0% found this document useful (0 votes)
6 views13 pages

Lect06 Part1 Week4

The document discusses multithreading in Java, explaining that it allows concurrent execution of multiple threads, each with its own execution path. It covers thread states, creation methods, and the importance of thread scheduling and priorities. Additionally, it provides examples of thread execution and blocking, emphasizing the efficiency of multithreaded programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

Lect06 Part1 Week4

The document discusses multithreading in Java, explaining that it allows concurrent execution of multiple threads, each with its own execution path. It covers thread states, creation methods, and the importance of thread scheduling and priorities. Additionally, it provides examples of thread execution and blocking, emphasizing the efficiency of multithreaded programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Programming2(CS272)

Dr Walid M. Aly

Lecture6
Threads

1
12:06
Introduction

• Operating systems on single-processor computers create the


illusion of concurrent execution by rapidly switching between
activities, but on such computers only a single instruction can
execute at once.
• Java makes concurrency available to you through the language
and APIs.
• You specify that an application contains separate threads of
execution
– each thread has its own method-call stack and program counter
– can execute concurrently with other threads while sharing application
wide resources such as memory with them.
• This capability is called multithreading.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
12:06
Multithreaded Programming
• A multithreaded program contains two or more parts that can run concurrently.
• Each part of such a program is called a thread, each thread defines a separate path
of execution.
• A thread is an object of class java.lang.Thread
• Multithreading enables you to write very efficient programs that make maximum
use of the CPU, because idle time can be kept to a minimum.
• Each java thread has a certain priority that can be used by operating systems to
handle scheduling.

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

• Thread scheduling is platform dependent

• Most programmers who use Java multithreading will


not be concerned with setting and adjusting thread
priorities.

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

1. DataInputStream din=new …….


2. int i=din.readInt()
3. ………………………..
4. …………………………..
5. ……………………………………
..

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

You might also like