Tải bản đầy đủ (.pdf) (58 trang)

Chapter 1 Multithreading

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (805.21 KB, 58 trang )

Chapter 1
Multithreading
Lecturer: Hồ Tiến Lâm
Contents
 Threads Introduction
 Interrupting Threads
 Thread States
 Thread Properties

Synchronization

Synchronization
 Callables and Futures
2
GV. Hồ Tiến Lâm
Contents
 Threads Introduction
 Interrupting Threads
 Thread States
 Thread Properties

Synchronization

Synchronization
 Callables and Futures
3
GV. Hồ Tiến Lâm
Threads Introduction
 Multitasking: the ability to have more than one program
working at what seems like the same time.
 Programs that can run more than one thread at once are


called mutithreaded programs.
 What is the difference between multiple processes and
multiple
threads
?
4
multiple
threads
?
GV. Hồ Tiến Lâm
Threads Introduction (cont.)
 Procedure for running a task in a separate thread:
1. Create a class that implements the Runnable interface and
put the code for doing task into that class:
public interface Runnable {
void run()
}
5
}
class MyRunnable implements Runnable {
public void run() {
// put task code here
}
}
GV. Hồ Tiến Lâm
Threads Introduction (cont.)
2. Create an object of your class:
Runnable r = new MyRunnable();
3. Create a Thread object from the Runnable:
Thread t = new Thread(r);

6
4. Start the thread:
t.start();
GV. Hồ Tiến Lâm
Contents
 Threads Introduction
 Interrupting Threads
 Thread States
 Thread Properties

Synchronization

Synchronization
 Callables and Futures
7
GV. Hồ Tiến Lâm
Interrupting Threads
 In JDK 1.0, there was a stop method which is used to
terminate another thread. But it's now deprecated.
 Use the interrupt method to request termination of a
thread.
 To check if one thread was interrupted:
Thread.currentThread
().
isInterrupted
()
8
Thread.currentThread
().
isInterrupted

()
 If a thread is blocked, it cannot check the interrupted
status => throws InterruptedException
GV. Hồ Tiến Lâm
Interrupting Threads (cont.)
 public void run() {
try {

while (!Thread.currentThread().isInterrupted()
&& more work to do) {
do more work
}
} catch(InterruptedException e) {
// thread was interrupted during sleep or wait
9
// thread was interrupted during sleep or wait
} finally {
cleanup, if required
}
// exiting the run method terminates the thread
}
 The sleep method throws an
InterruptedException if you call it when the
interrupted status is set.
GV. Hồ Tiến Lâm
Interrupting Threads (cont.)
 public void run() {
try {

while (more work to do) {

do more work
Thread.sleep(delay);
}
} catch(InterruptedException e) {
10
} catch(InterruptedException e) {
// thread was interrupted during sleep or wait
} finally {
cleanup, if required
}
// exiting the run method terminates the thread
}
GV. Hồ Tiến Lâm
Contents
 Threads Introduction
 Interrupting Threads
 Thread States
 Thread Properties

Synchronization

Synchronization
 Callables and Futures
11
GV. Hồ Tiến Lâm
Thread States
 There are 4 states:
• New
• Runnable
• Blocked

• Dead
New Threads:
12

New Threads:
• When you create a thread with new operator, the thread is not
yet running.
GV. Hồ Tiến Lâm
Thread States (cont.)
 Runnable Threads:
• When you invoke the start method, the thread is runnable.
• Why is the state called “runnable” and not “running”?
A runnable thread may or may not be running at any given
time.

It is up to the OS to give the thread time to run (
time
-
slicing
)
13

It is up to the OS to give the thread time to run (
time
-
slicing
)
GV. Hồ Tiến Lâm
Thread States (cont.)
 Blocked Threads:

• The thread goes to sleep by calling the sleep method.
• The thread calls an operation that is blocking on input/output.
• The thread tries to acquire a lock that is currently held by
another thread.

The thread waits for a condition.
14

The thread waits for a condition.
• Calls the suspend method of the thread. However, this
method is deprecated.
GV. Hồ Tiến Lâm
Thread States (cont.)
15
GV. Hồ Tiến Lâm
Thread States (cont.)
 Dead Threads:
• It dies a natural death because the run method exits normally.
• It dies abruptly because an uncaught exception terminates the
run method.
• To check if a thread is currently alive (runnable or blocked), use
the
isAlive
method.
16
the
isAlive
method.
• NOTE: You cannot find out if an alive thread is runnable or
blocked, or if a runnable thread is running.

GV. Hồ Tiến Lâm
Contents
 Threads Introduction
 Interrupting Threads
 Thread States
 Thread Properties

Synchronization

Synchronization
 Callables and Futures
17
GV. Hồ Tiến Lâm
Thread Priorities
 In Java, every thread has a priority.
 You can change the priority of any thread with the
setPriority method.
 Range of priority:
• Thread.MIN_PRIORITY: 1
• Thread.NORM_PRIORITY: 5
• Thread.MAX_PRIORITY: 10
 Thread priorities are highly system dependent.
18
GV. Hồ Tiến Lâm
Thread Priorities (cont.)
 You should never structure your programs so that their
correct functioning depends on priority levels.
 If you have several threads with a high priority that rarely
block, the lower-priority threads may never execute.
 You cause the executing thread to yield by using

. If other runnable threads have a
Thread.yield()
. If other runnable threads have a
priority at least as high as the priority of this thread, they
will be scheduled next.
19
GV. Hồ Tiến Lâm
Daemon Threads
 You can turn a thread into a daemon thread by calling
t.setDaemon(true);
 A daemon is simply a thread that has no other role in life
than to serve others.
20
GV. Hồ Tiến Lâm
Thread Groups
 This helps you simultaneously work with a group of
threads.
 Construct a thread group:
String groupName = ; // this name must be
unique
ThreadGroup
g = new
ThreadGroup
g = new
ThreadGroup(groupName);
 Add a thread to the thread group:
Thread t = new Thread(g, threadName);
 To check whether any threads of a particular group are
still runnable, use the activeCount method.
21

GV. Hồ Tiến Lâm
Thread Groups (cont.)
 To interrupt all threads in a thread group:
g.interrupt(); // g: an object of ThreadGroup
 Thread groups can have child subgroups. You can specify
the parent group in the constructor, or by default a newly
created thread group becomes a child of the current thread
group.
group.
 Method activeCount and interrupt refer to all
threads in their group and all child groups.
22
GV. Hồ Tiến Lâm
Contents
 Threads Introduction
 Interrupting Threads
 Thread States
 Thread Properties

Synchronization

Synchronization
 Callables and Futures
23
GV. Hồ Tiến Lâm
Synchronization
 What happen if two threads have access to the same object
and each calls a method that modifies the state of the
object?
 Depending on the order in which the data were accessed,

corrupted objects can result.
That situation is called a
race
condition.

That situation is called a
race
condition.
24
GV. Hồ Tiến Lâm
An Example of a Race Condition
 We simulate a bank with 100 accounts.
 We randomly generate transactions that move money
between these accounts.
 Each account has one thread.

Each transaction moves a random amount of money from

Each transaction moves a random amount of money from
the account to another random account.
 The fact: total amount of money in all accounts does NOT
change whatever we run program for a long time.
25
GV. Hồ Tiến Lâm
LET’S SEE THE DEMO!

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×