0% found this document useful (0 votes)
5 views43 pages

6. Threads

Addmissita recognizia

Uploaded by

Cherif Aidou
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)
5 views43 pages

6. Threads

Addmissita recognizia

Uploaded by

Cherif Aidou
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/ 43

Threads

Multithreading
• A program may consist of many tasks that can run
concurrently.
• A thread is the flow of execution, from beginning to end,
of a single task.
• Multithreading enables multiple tasks in a program to be
executed concurrently.
• In single-processor systems, the multiple threads share
CPU time,
• In multi-processor systems, different treads can be
allocated different processors.
• The operating system is responsible for scheduling and
allocating resources to the threads.
Multithreading

(a) Multiple threads are running on (b) Multiple threads share a single CPU.
multiple CPUs.
Multithreading
• Most of the time the CPU is idle. It does nothing.
– Example, while waiting for the user to enter data.
• The idle state can be exploited to execute other tasks
or threads.
• Multithreading can make your program more
responsive and interactive, as well as enhance
performance.
– For example, a word processor lets you print or save a file
while you are typing.
• Usually, multithreaded programs run faster than single-
threaded programs even on single-processor systems.
Threads in Java
• Java provides good support for creating and running threads and for
locking resources to prevent conflicts.

• When your program executes, the Java interpreter starts a first


thread for the main method.

• You can create many other threads for other tasks that might be
executed concurrently.

• All the created threads in an application belong to the same


process.

• Threads run independently but might share resources, like memory,


I/O devices, etc.
Creating a thread in Java
We can create Threads in java using two different
ways:

1. Extending Thread Class

2. Implementing a Runnable interface


Extending Thread Class
• The Thread Class provides constructors and methods for
creating and performing operations on a Thread,
• Any class that extends Thread can run as a method,
• The run() method of Thread must be overloaded to perform
the desired task
• To effectively create the new thread:
– An instance of its class should created
– The start() method must be invoked on the created
instance
Extending Thread class
public class MyThread extends Thread {
// overload run method for the new Thread
public void run()
{ //The task the thread performs goes here
System.out.println("Thread Started Running...");
}
public static void main(String[] args)
{ //Instantiate an object from MyThread
MyThread t = new MyThread ();
// Invoking Thread using start() method
t.start();
}
}
Implementing the Runnable interface
The second way of creating a thread is
• To implement the Runnable interface by the class
which performs the task.
• Similar to the previous way, the run() method must
be overloaded to perform the expected task.
• An object of created class is the instantiated.
• The thread is created by passing the object to the
Thread class constructor takes.
• The start() method of the Thread object is invoked
Implementing the Runnable interface
public class MyTask implements Runnable {
// overload run method for the new Task
public void run()
{ //The task the thread performs goes here
System.out.println("Thread Started Running...");
}
public static void main(String[] args)
{ //Instantiate an object from MyTask
MyTask tsk = new MyTask ();
// instancialte a Thread object pasing tsk to the constructor
Thread t = new Thread(tsk)
// Invoking Thread using start() method
t.start();
}
}
Method1: example 2
public class ReadInventoryThread extends Thread{
public void run() {
System.out.println("Printing zoo inventory");
}
public static void main(String[] args) {
(new ReadInventoryThread()).start();
}
}
Method2: example 2
public class PrintData implements Runnable {
public void run() {
for(int i=0; i<3; i++)
System.out.println("Printing record: "+i);
}

public static void main(String[] args) {


(new Thread(new PrintData())).start();
}
}
Both methods at a time
public static void main(String[] args) {
System.out.println("begin");
(new ReadInventoryThread()).start();
(new Thread(new PrintData())).start();
(new ReadInventoryThread()).start();
System.out.println("end");
}

The output will not always be the same.


Runnable interface
Runnable defines a single method run()

Interface Runnable()
{ void run(); }
Thread Class

Among the Thread class methods, the most used are :

Method Meaning
getName Obtain a thread’s name
getPriority Obtain a thread’s 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

Note that Thread class implements Runnable interface


getName / setName
• getName() Returns the name of the thread
• The main thread name is Main
• Other created threads names are set to
Thread-n, n is a sequential number of order of
creating the thread
• A thread name can be changed by invoking
setName(“thread name’’)
getName/setName
public static void main(String[] args) {
System.out.println("begin");
Thread t1=new ReadInventoryThread(); begin
Thread t2= new Thread(new PrintData()); Thread-0
Thread t3= new ReadInventoryThread(); Thread-1
Thread-2
System.out.println(t1.getName()); t1
System.out.println(t2.getName());
t2
t3
System.out.println(t3.getName());
end
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");

System.out.println(t1.getName());
System.out.println(t2.getName());
System.out.println(t3.getName());
System.out.println("end");
}
Thread priority
• A thread's priority is an integer in the range 1 to 10.
• The larger the integer, the higher the priority.
• The thread scheduler uses the priority to determine which
one should be allowed to execute first.
• The Thread class defines three priority types as
constants MIN_PRIORITY, NORM_PRIORITY, and
MAX_PRIORITY, with values 1, 5, and 10, respectively.
• NORM_PRIORITY is the default priority for a new Thread.
• The priority is retrieved using getPriority() method and
modified using setPriority() method
toString
toString() method is used to extract the thread's Id,
name, priority, and thread group as a string.

Thread t1=new ReadInventoryThread();


Thread t2= new Thread(new PrintData());
System.out.println(t1.toString());
System.out.println(t2.toString());
Output :
Thread[#19,Thread-0,5,main]
Thread[#20,Thread-1,5,main]
currentThread()
• A reference to the current thread can be obtained by invoking
currentThread() method of Thread class in the thread
code;

static Thread currentThread( )

• The main thread, for example, can be manipulated using the


obtained reference we obtain by invoking currentThread in
main.
currentThread()
class CurrentThreadDemo {

public static void main(String args[]){

Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
t.setName("My Main Thread");

System.out.println("After name change: " + t);


}
}
sleep( )
The sleep( ) method causes the thread from which it is
called to suspend execution for the specified period of
milliseconds. Its general form is shown here:

static void sleep(long milliseconds) throws


InterruptedException
sleep()
class ThreadDemo {
public static void main(String args[]){
Thread t = Thread.currentThread();
try{
for(int n = 5; n>0; n--){
System.out.println(n);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println("Main thread
interrupted");
}
}
}
start()
• The call to start the launches the task defined in
the run method in a new separate thread.

• If not called the thread is not created.

• If we invoke the run method, this runs the code


but no new thread is created. It is run in the
invoking thread.
start()

public static void main(String[] args) {


System.out.println("begin");
(new ReadInventoryThread()).start();
(new Thread(new PrintData())).start();
(new ReadInventoryThread()).start();
System.out.println("end");
}
start()
The output is that it is unknown until runtime. For
example, the following is just one possible output:
begin
Printing zoo
inventory Printing
record: 0
end
Printing zoo
inventory Printing
record: 1
Printing record: 2
26
Run()

public static void main(String[] args) {


System.out.println("begin");
(new ReadInventoryThread()).run();
(new Thread(new PrintData())).run();
(new ReadInventoryThread()).run();
System.out.println("end");
}
Run()
The output will always be the following, no thread
created here:

begin
Printing zoo inventory Printing record: 0
Printing record: 1
Printing record: 2 Printing zoo inventory
end
start vs. run
Main difference is that when program calls start() method a new
Thread is created and code inside run() method is executed in
new Thread while if you call run() method directly no new
Thread is created and code inside run() will execute on the
current Thread.
join( )
• wait for a thread to finish :

final void join( ) throws


InterruptedException

• This method waits until the thread on which it is


called terminates.
Join()
class NewThread implements Runnable { String name;
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
}
public void run() {
for (int i=3; i>0; i--)
System.out.println("Child_thread:"+i);
System.out.println("Exiting child thread.");
}
}
class RunThread {
public static void main(String[] args) {
NewThread nt1 = new NewThread("One"); nt1.t.start(); nt1.t.join();
NewThread nt2 = new NewThread("Two"); nt2.t.start(); nt2.t.join();
NewThread nt3 = new NewThread("Three");nt3.t.start();nt3.t.join();
System.out.println("Main thread finished");
}
} 49
Join()
• The first joint: causes the main thread to stop
running until thread one finishes.
• Then, main thread resumes creating thread
two, starting it and waiting it to finish by
calling join.
• Same thing happens for the third thread.
Join()
New thread: Thread[One,5,main]
Child thread: 3
Child thread: 2
Child thread: 1
Exiting childthread.
New thread: Thread[Two,5,main]
Child thread: 3
Child thread: 2
Child thread: 1
Exiting childthread.
New thread: Thread[Three,5,main]
Child thread: 3
Child thread: 2
Child thread: 1
Exiting childthread.
Main thread finished
isAlive( )
You can call isAlive( ) on the thread to kow if it has
finished.

final boolean isAlive( )

The isAlive( ) method returns true if the thread


upon which it is called is still running. It returns
false otherwise.
isAlive( )
class NewThread extends Thread {
public void run() {
for (int i=2; i>0; i--)
System.out.println("Child thread: "+i);
System.out.println("Exiting child thread.");
}
}

class RunThread {
public static void main(String[] a)
throws InterruptedException{
NewThread nt1 = new NewThread();
System.out.println("IsAlive():" + nt1.isAlive());
nt1.start();
System.out.println("IsAlive():"+nt1.isAlive());
nt1.join();
System.out.println("IsAlive():" +nt1.isAlive());
}
}
isAlive( )
IsAlive():false
IsAlive():true
Child thread: 2
Child thread: 1
Exiting child thread.
IsAlive():false
Thread life cycle
• A thread can be in one of five states: New, Ready, Running, Blocked,
or Finished.
Life Cycle Of Thread
• When a thread is newly created, it enters the New state.
• After a thread is started by calling its start() method, it enters the Ready
state. A ready thread is runnable but may not be running yet. The
operating system has to allocate CPU time to it.
• When a ready thread begins executing, it enters the Running state. A
running thread can enter the Ready state if its given CPU time expires or
its yield() method is called.
• A thread can enter the Blocked state (i.e., become inactive) for several
reasons. It may have invoked the join(), sleep(), or wait() method.
– It may be waiting for an I/O operation to finish.
– A blocked thread may be reactivated when the action inactivating it is
reversed. For example, if a thread has been put to sleep and the sleep time
has expired, the thread is reactivated and enters the Ready state.
• Finally, a thread is Finished if it completes the execution of its run()
method.
Synchronization
When two or more threads need 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.
Example
public class Counter extends Thread{
public static int counter = 0;
public void run() {
++Counter.counter;
}
public static void main(String[] a) throws InterruptedExcept
{ for(int i = 0; i<10; i++)
(new Counter()).start();

currentThread().sleep(10000);
System.out.println(counter);
}
}
Problem!
• Counter is shared between all created threads;
• Its value maybe altered
• Example:
• Thread 1 reads counter then interrupted
• Thread 2 increment counter and terminates
• Thread 1 resumes, increment counter using its old
value
Synchronized solves the problem
public class Counter extends Thread{
public static int counter = 0;
Object monitor;
public Counter(Object monitor) {
this.monitor = monitor;}
public void run() {
synchronized (monitor) {
++Counter.counter;}
}
public static void main(String[] args) throws
InterruptedException {
Object monitor = new Object();
for(int i = 0; i<10; i++)
(new Counter(monitor)).start();
currentThread().sleep(1000);
System.out.println(counter)
}
}
• Thread offers many other methods and
mechanisms for communication between
threads and synchronization
• Inter-thread communication is beyond this
lecture

You might also like