Sie sind auf Seite 1von 49

1

Threads in Java
(Deitel & Deitel)
OOutline
1- Introduction
1- Class Thread: An Overview of the Thread Methods
1- Thread States: Life Cycle of a Thread
1- Thread Priorities and Thread Scheduling
1- Thread Synchronization
1- Daemon Threads
1- Runnable Interface
1- Thread Groups

Prentice Hall, Inc. All rights reserved.


2

Introduction

• Performing operations concurrently (in parallel)


– We can walk, talk, breathe, see, hear, smell... all at the same time
– Computers can do this as well - download a file, print a file,
receive email, run the clock, more or less in parallel….
• How are these tasks typically accomplished?
• Operating systems support processes
• What’s the difference between a process and a thread?
• Processes have their own memory space, threads share memory
• Hence processes are “heavyweight” while threads are “lightweight”
– Most programming languages do not allow concurrency
– Java supports concurrency as part of language and libraries
– What other languages support concurrency in the
language?{C#,ADVANCED FORTRAN,SCALA}

Prentice Hall, Inc. All rights reserved.


3

What and why

• Threads of execution
– Each thread is a portion of a program that can execute
concurrently with other threads (multithreading)
• C and C++ are single-threaded
• Gives Java powerful capabilities not found in C and C++
– Example: downloading a video clip
• Instead of having to download the entire clip then play it:
• Download a portion, play that portion, download the next
portion, play that portion... (streaming)
• Ensure that it is done smoothly
– Other example applications of multi-threading?{GUI
application , computer games}

Prentice Hall, Inc. All rights reserved.


4

Portability difference (JVM)

• Portability
– Differences between platforms (e.g., Solaris, Windows, …)
• On Solaris (Linux?)
– A thread runs to completion or until a higher priority thread
becomes ready
– Preemption occurs (processor is given to the higher-priority
thread)
• On Win32 (Windows 9x, NT, XP)
– Threads are timesliced
• Thread given quantum of time to execute
• Processor then switched to any threads of equal
priority(CONTEXT SWITCHING)
– Preemption occurs with higher and equal priority threads
Prentice Hall, Inc. All rights reserved.
5

TERMS RELATED
• Context Switching

• Preemptive switch

• Synchronization

• Messaging

Prentice Hall, Inc. All rights reserved.


6

An Overview of the Thread Methods

• Thread-related methods
– Constructors
• Thread() - Creates a thread with an auto-numbered name
of format Thread-1, Thread-2...
• Thread( threadName ) - Creates a thread with name
– run
• Does “work” of a thread – What does this mean?
• Can be overridden in subclass of Thread or in Runnable
object (more on interface Runnable elsewhere)
– start
• Launches thread, then returns to caller
• Calls run
• Error to call start twice for same thread

Prentice Hall, Inc. All rights reserved.


Thread States: Life Cycle of a Thread

Threads can be in one of the states


NewBorn, Runnable,Running, Blocked,Waiting,Sleeping and Dead

A thread's state changes based on:

Control methods such as start, sleep, yield, wait, notify


Termination of the run method

Prentice Hall, Inc. All rights reserved.


8

Prentice Hall, Inc. All rights reserved.


9

Thread States: Life Cycle of a Thread

• Born state
– Thread just created
– When start called, enters runnable state
• (Ready state) Runnable state
– Highest-priority ready thread enters running state
• Running state
– System assigns processor to thread (thread begins executing)
– When run completes or terminates, enters dead state
• Dead state
– Thread marked to be removed by system
– Entered when run terminates or throws uncaught exception

Prentice Hall, Inc. All rights reserved.


10

Other Thread States


• Blocked state
– Entered from running state
– Blocked thread cannot use processor, even if available
– Common reason for blocked state - waiting on I/O request
• Sleeping state
– Entered when sleep method called
– Cannot use processor
– Enters ready state after sleep time expires
• Waiting state
– Entered when wait called in an object thread is accessing
– One waiting thread becomes ready when object calls
notify
– notifyAll - all waiting threads become ready

Prentice Hall, Inc. All rights reserved.


11

More Thread Methods


• static void sleep( long milliseconds )
– Thread sleeps (does not contend for processor) for number of
milliseconds
– Why might we want a program to invoke sleep?
– Can give lower priority threads a chance to run
• void interrupt() - interrupts a thread
• boolean isInterrupted()
– Determines if a thread is interrupted
• boolean isAlive()
– Returns true if start called and thread not dead (run has not
completed)
• getPriority() - returns this thread's priority
• setPriority() – sets this threads priority
• getname()-get name of a thread
• Join()-wait for a thread to terminate.
• Yield():thread yields processor to threads of equal priority
• Useful for non-timesliced systems, where threads run to
completion
Prentice Hall, Inc. All rights reserved.
Prentice Hall, Inc. All rights reserved.
13

Prentice Hall, Inc. All rights reserved.


14

Prentice Hall, Inc. All rights reserved.


Get name() method
Prentice Hall, Inc. All rights reserved.
setName()
Prentice Hall, Inc. All rights reserved.
17

Creating a thread
• Extending a “Thread” class
-override run() method
constructor: public Thread(String threadName)

• Implimenting “Runnable ” interface

-implement run() method


//public void run()
constructor: Thread(Runnable threadOb, String threadName)

Prentice Hall, Inc. All rights reserved.


18

Output
• Child thread: Thread[Demo Thread,5,main]
• Main Thread: 5
• Child Thread: 5
• Child Thread: 4
• Main Thread: 4
• Child Thread: 3
• Child Thread: 2
• Main Thread: 3
• Child Thread: 1
• Exiting child thread.
• Main Thread: 2
• Main Thread: 1
• Main thread exiting.

Prentice Hall, Inc. All rights reserved.


19

Thread Scheduling Example

• Demonstrates basic threading techniques:


– Create a class derived from Thread
– Use sleep method
• What it does:
– Create threads, which sleep for random amount of time
– After they finish sleeping, print their name
• Program has two classes:
– NewThread
• Derives from Thread
• Instance variable sleepTime
– Extendthread
• Creates objects

Prentice Hall, Inc. All rights reserved.


• class NewThread extends Thread { class ExtendThread {
• NewThread() {
public static void main(String args[])
• // Create a new, second thread {
• super("Demo Thread");
new NewThread(); // create a new
• System.out.println("Child thread: " +this);
thread
• start(); // Start the thread
• } try {
• // This is the entry point for the second for(int i = 5; i > 0; i--) {
thread. System.out.println("Main Thread: " +
• public void run() { i);
• try {
Thread.sleep(1000);
• for(int i = 5; i > 0; i--) {
• System.out.println("Child Thread: " + i); }
• Thread.sleep(500); } catch (InterruptedException e) {
• } System.out.println("Main thread
• } catch (InterruptedException e) { interrupted.");
• System.out.println("Child interrupted."); }
• }
System.out.println("Main thread
• System.out.println("Exiting child exiting.");
thread.");
• } }
• } } public Thread(String threadName)
Prentice Hall, Inc. All rights reserved.
21

Output
• Child thread: Thread[Demo Thread, 5 , main]
• Main Thread: 5
• Child Thread: 5
• Child Thread: 4
• Main Thread: 4
• Child Thread: 3
• Child Thread: 2
• Main Thread: 3
• Child Thread: 1
• Exiting child thread.
• Main Thread: 2
• Main Thread: 1
• Main thread exiting.

Prentice Hall, Inc. All rights reserved.


22

Runnable Interface

• Java does not support multiple inheritance


– Instead, use interfaces
– Until now, we inherited from class Thread, overrode run
• Multithreading for an already derived class
– Implement interface Runnable (java.lang)
• New class objects "are" Runnable objects
– Override run method
• Controls thread, just as deriving from Thread class
• In fact, class Thread implements interface Runnable
– Create new threads using Thread constructors
• Thread( runnableObject )
• Thread( runnableObject, threadName )

Prentice Hall, Inc. All rights reserved.


23

Runnable Interface example

• Upcoming example program

Prentice Hall, Inc. All rights reserved.


• // Create a second thread. • class ThreadDemo {
• class NewThread implements Runnable { • public static void main(String args[]) {
• Thread t; • new NewThread(); // create a new
• NewThread() { thread
• // Create a new, second thread • try {
• t = new Thread(this, "Demo Thread"); • for(int i = 5; i > 0; i--) {
• System.out.println("Child thread: " + t); • System.out.println("Main Thread: " +
i);
• t.start(); // Start the thread
• Thread.sleep(1000);
• }
• }
• // This is the entry point for the second
thread. } catch (InterruptedException e)
• public void run() { {
• try { System.out.println("Main thread
• for(int i = 5; i > 0; i--) { interrupted.");
• System.out.println("Child Thread: " + i); }
• Thread.sleep(500);
System.out.println("Main thread
• } exiting.");
• } catch (InterruptedException e) {
}
• System.out.println("Child interrupted.");
• } }
• System.out.println("Exiting child thread.");
• } t = new Thread(this, "Demo Thread");
• }

Prentice Hall, Inc. All rights reserved.


25

Output
• Child thread: Thread[Demo Thread,5,main]
• Main Thread: 5
• Child Thread: 5
• Child Thread: 4
• Main Thread: 4
• Child Thread: 3
• Child Thread: 2
• Main Thread: 3
• Child Thread: 1
• Exiting child thread.
• Main Thread: 2
• Main Thread: 1
• Main thread exiting.

Prentice Hall, Inc. All rights reserved.


26

Thread Priorities and Scheduling


• Java scheduler
– Keeps highest-priority thread running at all times
– If timeslicing available, ensure equal priority threads
executed
– New high priority threads could postpone execution of lower
priority threads
• Indefinite postponement (starvation)
• Priority methods
– setPriority( int priorityNumber )
final void setPriority ( int level)
Level:new priority setting for calling thread.
– getPriority()
final int getPriority( )
For getting current priority setting
Prentice Hall, Inc. All rights reserved.
27

Thread Priorities and Scheduling

• All Java applets / applications are multithreaded


– Threads have priority from 1 to 10
• Thread.MIN_PRIORITY - 1
• Thread.NORM_PRIORITY - 5 (default)
• Thread.MAX_PRIORITY - 10
• New threads inherit priority of thread that created it
• These priorities are defined as static final variables within
Thread.
• Timeslicing
– Each thread gets a quantum of processor time to execute
• After time is up, processor given to next thread of equal
priority (if available)
– Without timeslicing, each thread of equal priority runs to
completion
Prentice Hall, Inc. All rights reserved.
Prentice Hall, Inc. All rights reserved.
Prentice Hall, Inc. All rights reserved.
currentThread().getPriority()

Prentice Hall, Inc. All rights reserved.


31

Thread Synchronization

• Monitors
define?
Java monitor
– Object with synchronized methods
• Any object can be a monitor
– Methods declared synchronized
• public synchronized int myMethod( int x )
• Only one thread can execute a synchronized method at
a time
– Obtaining the lock and locking an object
• If multiple synchronized methods, only one may be active
– Java also has synchronized blocks of code

Prentice Hall, Inc. All rights reserved.


32

Thread Synchronization

• Thread may decide it cannot proceed


– May voluntarily call wait while accessing a
synchronized method
• Removes thread from contention for monitor object and
processor
• Thread in waiting state
– Other threads try to enter monitor object
• Suppose condition first thread needs has now been met
• Can call notify to tell a single waiting thread to enter ready
state
• notifyAll - tells all waiting threads to enter ready state

Prentice Hall, Inc. All rights reserved.


33

Synchonized blocks

• Synchronized blocks of code


synchronized( monitorObject ){
...
}
– monitorObject- Object to be locked while thread executes block
of code – Why?
• Suspending threads
– In earlier versions of Java, there were methods to
stop/suspend/resume threads
• Why have these methods been deprecated?
• Dangerous, can lead to deadlock
– Instead, use wait and notify
• wait causes current thread to release ownership of a monitor
until another thread invokes the notify or notifyAll method
• Why is this technique safer?
Prentice Hall, Inc. All rights reserved.
34

Synchronized block & method

• Synchronized keyword creates a block of code


called critical section .
• To enter a critical section a thread needs a
corresponding object’s lock

Prentice Hall, Inc. All rights reserved.


Prentice Hall, Inc. All rights reserved.
Prentice Hall, Inc. All rights reserved.
Prentice Hall, Inc. All rights reserved.
38

Interthread communication
• Used to allow synchronized threads to
communicate with each other.
• Methods
Wait()
Notify()
NotifyAll()

Prentice Hall, Inc. All rights reserved.


39

Contd..
• Wait()
causes current thread to release the lock and wait
until:
1. the specified time elapsed
2. Another thread calls notify() or notifyAll()
• Notify()
call notify to tell a single waiting thread to
enter ready state
• NotifyAll()
- tells all waiting threads to enter ready state

Prentice Hall, Inc. All rights reserved.


40

Producer consumer problem


• To make sure that the producer won’t try to add data into the buffer if
it’s full and that the consumer won’t try to remove data from an empty
buffer.

• Solution
The producer is to either go to sleep or discard data if the buffer is full.
The next time the consumer removes an item from the buffer, it
notifies the producer, who starts to fill the buffer again. In the same
way, the consumer can go to sleep if it finds the buffer to be empty.
The next time the producer puts data into the buffer, it wakes up the
sleeping consumer.
An inadequate solution could result in a deadlock where both
processes are waiting to be awakened.

Prentice Hall, Inc. All rights reserved.


Prentice Hall, Inc. All rights reserved.
// Create producer thread 42
• import java.util.LinkedList;
Thread t1 = new Thread(new Runnable()

{
• public class Threadexample
• { @Override
public static void main(String[] args) public void run()
throws InterruptedException {
• { try
• // Object of a class that has both
{
produce()
pc.produce();
• // and consume() methods
}
• final PC pc = new PC(); catch(InterruptedException e)
• {
• e.printStackTrace();
}
}
});

Prentice Hall, Inc. All rights reserved.


43
• // Create consumer thread
• Thread t2 = new Thread(new Runnable()
• {
• @Override
• public void run()
• {
• try
• {
• pc.consume();
• }
• catch(InterruptedException e)
• {
• e.printStackTrace();
• }
• }
• }); // Start both threads
• t1.start();
• t2.start();

• // t1 finishes before t2
• t1.join();
• t2.join();
Prentice Hall, Inc. All rights reserved.
44

• // This class has a list, producer (adds items to list


• // and consumer (removes items)

• public static class PC


• {
• // Create a list shared by producer and consumer
• // Size of list is 2.
• LinkedList<Integer> list = new LinkedList<>();
• int capacity = 2;

Prentice Hall, Inc. All rights reserved.


• public void produce() throws InterruptedException 45

• {
• int value = 0;
• while (true)
• {
• synchronized (this)
• {
• while (list.size()==capacity)
• wait();//GIVING INTRINSIC LOCK ON PC AND GO ON
WAITING

• System.out.println("Producer produced-" + value);
• // to insert the jobs in the list
• list.add(value++);
• // notifies the consumer thread that now it can start consuming
notify();
• Thread.sleep(1000);
• }
• }
• }
Prentice Hall, Inc. All rights reserved.
• // Function called by consumer thread System.out.println("Consumer consumed- 46
”+val);
• public void consume() throws
InterruptedException
• { // Wake up producer thread
• while (true) notify();
• {
• synchronized (this)
// and sleep
• {
• // consumer thread waits while Thread.sleep(1000);
//list is empty }
• while (list.size()==0)
}
• wait();//GIVE INTRINSIC
LOCK ON PC AND NOTIFY }
PRODUCER }

}
• //to retrive the ifrst job in the list
• int val = list.removeFirst();

Prentice Hall, Inc. All rights reserved.


47

OUTPUT

Prentice Hall, Inc. All rights reserved.


48
isalive()

final boolean isAlive( )


The isAlive( ) method returns true if the thread upon which it is called is still running. It
returns false otherwise.

Prentice Hall, Inc. All rights reserved.


49

Join()

final void join( ) throws InterruptedException


This method waits until the thread on which it is called terminates.

Prentice Hall, Inc. All rights reserved.

Das könnte Ihnen auch gefallen