6. Threads
6. 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.
• You can create many other threads for other tasks that might be
executed concurrently.
Interface Runnable()
{ void run(); }
Thread Class
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
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 t = Thread.currentThread();
System.out.println("Current thread: " + t);
t.setName("My Main Thread");
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 :
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