0% found this document useful (0 votes)
16 views22 pages

Chapt7-Threads (Updated)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views22 pages

Chapt7-Threads (Updated)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 22

Chapter 5

Threads

- Threads
- Basic Control of Threads
- Thread Interaction
- Putting It Together

Suzana/Java II-Chapt2
Objectives

• Define thread
• Understanding multithreading concept
• Creating threads by extending the Thread

class
• Understand thread controls and
communication
• Define thread groups

Suzana/Java II-Chapt2
What is thread ?

• A thread is the flow of execution of a task in a


program from beginning to end.
• Eg :

Thread 1

Thread 2

Thread 3

Figure 1 : Multiple threads are running on multiple CPUs

Suzana/Java II-Chapt2
Multithreading

• Multithreading is the capability of running multiple


tasks concurrently within a program
• With Java you can launch multiple threads from a
program concurrently. Eg :

Thread 1

Thread 2

Thread 3

Figure 2 : Multiple threads share a single CPU

Suzana/Java II-Chapt2
Creating custom threads class
by extending Thread class

Write a program that creates and runs 3 threads:


i. The 1st thread prints the letter a 100 times
ii. The 2nd thread prints the letter b 10 times
iii. The 3rd thread prints the integer 1 -100

Solution :
The program has 3 independent threads. To run
them concurrently, it needs to create a runnable
object for each thread. Because the first two
threads have similar functionality, they can be
defined in one thread class.

Suzana/Java II-Chapt2
Creating custom threads class
by extending Thread class
public class TestThread
{ /** main method */
public static void main(String[] args)
{
// creates 3 threads
PrintChar printA = new PrintChar('a', 100);
PrintChar printB = new PrintChar('b', 100);
PrintNum print100 = new PrintNum(100);

//starts the thread means telling the JVM that the threads are ready to run
print100.start();
printA.start();
printB.start();
}
} // end class

Suzana/Java II-Chapt2
// The thread class for printing a specified character
// in specified times
class PrintChar extends Thread
{ private char charToPrint; // The character to print
private int times; // The times to repeat

/** Construct a thread with specified character and


number of times to print the character */

public PrintChar(char c, int t)


{ charToPrint = c;
times = t;
}

/** Override the run() method to tell the system


what the thread will do */

public void run()


{ for (int i = 0; i < times; i++)
System.out.print(charToPrint);
}
} // end class
Suzana/Java II-Chapt2
// The thread class for printing number from 1 to n for a given n
class PrintNum extends Thread
{ private int lastNum;

/** Construct a thread for print 1, 2, ... i */


public PrintNum(int n)
{ lastNum = n;
}

/** Tell the thread how to run */


public void run()
{ for (int i = 1; i <= lastNum; i++)
System.out.print(" " + i);
}
} // end class

Suzana/Java II-Chapt2
Program output
3 threads running simultaneously on a single-CPU system..

The 3 threads will share the CPU time and take turns printing numbers
and letters on the console..
Suzana/Java II-Chapt2
Thread Controls and Communications
java.lang.Runnable

java.lang.Thread

Creates a default thread


+Thread()
Creates a thread for a specified task
+Thread(target: Runnable)
+start(): void Starts the thread that causes the run( ) method to be invoked

+interrupt(): void Interrupts this thread

+isAlive(): boolean Test whether the thread is currently running

+setPriority(p: int): void Sets priority p (1-10) for this thread

+join(): void Waits for this thread to finish

+sleep(millis: long): void Puts the runnable object to sleep for a specified time in milisecond

+yield(): void Causes this thread to pause temporarily and allow other threads to
execute

Figure 3 : The Thread Class contains


the methods/operations for controlling
the threads
Suzana/Java II-Chapt2
Thread operations :
1) yield()
public void run()
{ for (int i = 1; i <= lastNum; i++)
{ System.out.print(" " + i);
Thread.yield();
}
}

2) sleep()
public void run()
{ for (int i = 1; i <= lastNum; i++)
{ System.out.print(" " + i);
try {
if (i>=50) Thread.sleep(1);
}
catch(InterruptedException ex) {
}
}
}
Suzana/Java II-Chapt2
Thread operations (cont’):
3) join()
public void run()
{ for (int i = 1; i <= lastNum; i++)
{ System.out.print(" " + i);
try {
if (i==50) printA.join();
}
catch(InterruptedException ex) {
}
}
}

Suzana/Java II-Chapt2
join()
The joint() method is used to force one thread to wait for another thread to finish.

Thread t1 Thread t2

t2.join()

Wait for t2 to
finish

t2 finished

Using join() method

Suzana/Java II-Chapt2
Thread States
yield() / timeout run()
Running
returns
Thread
created start() run()
sleep() Finished
New Ready
join()
interrupt() wait()
Target
finishe
d
Wait for target Wait for Wait to be
to finish time out notified
notify()/notifyAll()
Time
Blocked out
interrupted()

A thread can be in one of the five states: New, Ready, Running, Blocked or Finished

Suzana/Java II-Chapt2
Thread States (cont)

• When a thread is newly created, it enters the New


state. After a thread is started by calling it
start(), it enters the Ready state. A Ready
thread is runnable but may not be running yet. The
OS has to allocate CPU time to it.
• When a Ready state begins executing, it enters
the Running state. A Running thread may enter
the Ready state if its given CPU time expires or
its yield() is called.
• A thread can enter the Blocked state (inactive) for
several reasons:
Suzana/Java II-Chapt2
Thread States (cont)

1. It may have invoked the join(), sleep() or


wait() or some other thread may have invoked
this methods.
2. It may be waiting for I/O operation to finish

• A Blocked thread is 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.
Suzana/Java II-Chapt2
Thread States (cont)

• Finally a thread is finished if it completes the


execution of its run()
• The isAlive() is used to find out the state of the
thread. It returns true if a thread is in the Ready,
Blocked or Running state: it returns false if a
thread is New and has not started or if it is
Finished.
• The interrupt() interrupts a thread in the following
way :

Suzana/Java II-Chapt2
Thread States (cont)

• If a thread is curently in the Ready or Running


state, its interrupted flag is set; if a thread is
currently Blocked, it is awakened and enters the
Ready state and a
java.lang.InterruptedException is thrown.

Suzana/Java II-Chapt2
Thread Priorities

• Java assign each thread priority.


• By default a thread inherits the priority of the thread that
spawned it
• You can increase or decrease the priority of the thread by
using the setPriority() and get the thread’s priority
using the getPriority()
• Priorities are numbers ranging from 1-10.
• The Thread class has the int constant MIN_PRIORITY,
NORM_PRIORITY and MAX_PRIORITY, representing 1, 5
and 10 respectively .

Suzana/Java II-Chapt2
Thread Priorities (cont)

• The JVM always picks the current runnable thread


with the highest priority. If several runnable thread
have equally high priorities, the CPU is allocated
to all of them in round–robin fashion.
• A lower-priority can run only when no higher-
priority threads are running.
• Eg :
print100.setPriority(Thread.MAX_PRIORITY);
// The print100 thread will finished first

Suzana/Java II-Chapt2
Thread Groups

• A thread groups is a set of threads


• Some program contain quite a few threads with
similar functionality. For convenience, you can
group them together and performs operations on
the entire group.
• For example, you can suspend or resume oll of
the threads in a group at the same time:
1. Use the ThreadGroup constructor to construct a thread group:
ThreadGroup g = new ThreadGroup(“thread group”) ;

This create a thread group g named “thread group”. The name is a


string and must be unique.
Suzana/Java II-Chapt2
Thread Groups (cont)

2. Using the Thread constructor , place a thread in a thread group:


Thread t = new Thread(g,new ThreadClass(), ”label for the thread ”);
This creates a thread and places it in the thread group g.

3. To find out how many threads in a group are currently running, use the
activeCount(). The following statements displays the active number of
threads in group g :
System.out.println(“ The number of runnanble threads in the group”
+ g.activeCount());

4. Each thread belongs to a thread group. To find which group a thread


belongs to, use the getThreadGroup()

Suzana/Java II-Chapt2

You might also like