• No results found

13 Multithreading pdf

N/A
N/A
Protected

Academic year: 2020

Share "13 Multithreading pdf"

Copied!
25
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 13: Multithreading

)

Threads Concept

)

Creating Threads by Extending the

Thread

class

)

Creating Threads by Implementing the

Runnable

Interface

)

Controlling Threads and Thread Status

)

Thread Groups

)

Synchronization

(2)

Threads Concept

Multiple

threads on

multiple

CPUs

Thread 3

Thread 2

Thread 1

Multiple

threads

sharing a

(3)

Creating Threads by Extending the

Thread

class

// Custom thread class

public class CustomThread extends Thread { ... public CustomThread(...) { ... }

// Override the run method in Thread public void run()

{

// Tell system how to run custom thread ...

} ... }

// Client class public class Client {

...

public someMethod() {

...

// Create a thread

CustomThread thread = new CustomThread(...); // Start a thread

(4)

Example 13.1

Using the

Thread

Class to

Create and Launch Threads

)

Objective: Create and run three threads:

– The first thread prints the letter

a

100 times.

– The second thread prints the letter

b

100

times.

(5)

Example 13.1

Using the

Thread

Class to

Create and Launch Threads, cont.

TestThread

Run

Click the Run button to access the DOS prompt; then

(6)

Creating Threads by Implementing

the

Runnable

Interface

// Custom thread class public class CustomThread implements Runnable { ... public CustomThread(...) { ... }

// Implement the run method in Runnable public void run()

{

// Tell system how to run custom thread ...

} ... }

// Client class public class Client {

...

public someMethod() {

...

// Create an instance of CustomThread CustomThread customThread

= new CustomThread(...); // Create a thread

Thread thread = new Thread(customThread); // Start a thread

thread.start(); ...

(7)

Example 13.2

Using the

Runnabel

Interface to

Create and Launch Threads

)

Objective: Create and run three threads:

– The first thread prints the letter

a

100 times.

– The second thread prints the letter

b

100

times.

– The third thread prints the integers 1 through

100.

Run

Click the Run button to access the DOS prompt;

then type

java TestRunnable

(8)

Controlling Threads

and Thread States

)

void run()

Invoked by the Java runtime system to execute the thread. You

must override this method and provide the code you want your

thread to execute.

)

void start()

Starts the thread, which causes the run() method to be invoked.

Called by the runnable object in the client class.

)

static void sleep(long millis)

throws InterruptedException

(9)

Controlling Threads

and Thread States

, cont.

)

void stop()

Stops the thread. (deprecated in JDK 1.2)

)

void suspend()

(deprecated in JDK 1.2)

Suspends the thread. Use the

resume()

method to resume.

)

void resume()

(deprecated in JDK 1.2)

(10)

Thread Priority

)

Each thread is assigned a default priority of

Thread.NORM_PRIORITY

. You can reset the

priority using

setPriority(int priority)

.

)

Some constants for priorities include

(11)

Thread States

Thread created

new

ready

running

finished

blocked

start

run

yield, or time

expired

stop or

complete

stop

suspend,

sleep, or wait

stop

(12)

Thread Groups

)

Construct a thread group using the

ThreadGroup

constructor:

ThreadGroup g = new ThreadGroup("timer

thread group");

)

Place a thread in a thread group using the

Thread

constructor:

(13)

Thread Groups, cont.

)

To find out how many threads in a group are

currently running, use the

activeCount()

method:

System.out.println("The number of “

+ “ runnable threads in the group ” +

(14)

Synchronization

A shared resource may be corrupted if it is

accessed simultaneously by multiple threads. For

example, two unsynchronized threads accessing

the same bank account causes conflict.

Step

balance thread[i]

thread[j]

1

0

newBalance = bank.getBalance() + 1;

2

0

newBalance = bank.getBalance() + 1;

3

1

bank.setBalance(newBalance);

(15)

Example 13.3

Showing Resource Conflict

)

Objective: create and launch 100 threads,

each of which adds a penny to a piggy bank.

Assume that the piggy bank is initially

(16)

Example 13.3, cont

PiggyBank

-balance

+getBalance +setBalance

1

100

PiggyBankWithoutSync

-PiggyBank bank -Thread[] thread

+main

Object

Object

AddAPennyThread

+run()

Thread

1

1

(17)

The

synchronized

keyword

To avoid resource conflicts, Java uses the

keyword

synchronized

to synchronize

method invocation so that only one thread can

be in a method at a time. To correct the

data-corruption problem in Example 13.3, you can

rewrite the program as follows:

(18)

Creating Threads for Applets

In Example 12.1, "Displaying a Clock," you drew a

clock to show the current time in an applet. The

clock does not tick after it is displayed. What can

you do to let the clock display a new current time

every second? The key to making the clock tick is

to repaint it every second with a new current time.

You can use the code given below to override the

(19)

Creating Threads for Applets

public void start()

{

while (true)

{

stillClock.repaint();

try

{

Thread.sleep(1000);

}

catch(InterruptedException ex)

{

}

}

}

(20)

Creating a Thread to run the

while

loop

public class MyApplet extends

JApplet implements Runnable

{ private Thread timer = null;

public void init()

{ timer = new Thread(this);

timer.start();

}

...

public void run()

{ ... }

(21)

Creating a Thread to run the

while

loop

, cont.

public void run()

{ while (true)

{ repaint();

try

{ thread.sleep(1000);

waitForNotificationToResume();

}

catch (InterruptedException ex)

{ }

(22)

Creating a Thread to run the

while

loop

, cont.

private synchronized void

waitForNotificationToResume()

throws InterruptedException

{

while (suspended)

wait();

(23)

Creating a Thread to run the

while

loop

, cont.

public synchronized void resume()

{

if (suspended)

{

suspended = false;

notify();

}

}

public synchronized void suspend()

{

(24)

Example 13.4 Displaying a

Running Clock in in an Applet

)

Objective: Simulate a running clock by using a

separate thread to repaint the clock.

ClockApplet

(25)

Example 13.5

Controlling a Group of Clocks

1

3

ClockGroup

-clockPanel1 -clockPanel2 -clockPanel3 -jbtResumeAll -jbtSuspendAll +jbtResumeAll() +jbtSuspendAll() +actionPerformed(e) +main +init()

JApplet

ClockPanel

-jlblTitle -clock jbtResume -jbtSuspend +setTitle(String title) +resume() +suspend() +actionPerformed(e)

Clock

+run() +suspend() +resume()

StillClock

1

1

ActionListener

Runnable

References

Related documents

These include analysis of timber enterprise survey data, an analysis of ACIAR tree measurement data, collation of the Barangay Chairmen Tree Farm Inventory data, interviews

♦  Creating a new thread, switching, and synchronizing threads are done via user-level procedure call. ♦  User-level thread operations 100x faster than

Major topics that will be covered include: Hardware concepts of parallel and distributed systems, software concepts and design issues, threads and thread usage,

In this section, the channel model is assumed to be selective fading channel, where the parameters of the channel in this case corresponding to multipaths where two paths are

The Employment Life Cycle (At a Glance) Workforce Staffing & Planning Position Management Hiring & Onboarding Performance Management Employee Relations/

ing the exits status of the terminated thread { thr join in other processes, or the current thread cannot wait for detached threads, threads. Thread Suspend

• The number of car accidents caused by faulty brakes, like the number caused by faulty wiring, have increased significantly since regulations on manufacturing were relaxed9. •

REVISED Due Dates, 2020 TTI 1 Strategic plan basics 1 st Draft of Plan due To SPA team March 2-5 Webinar Needs assessment March 24 May 15 [email protected] 2020 SP