8. Java concurrency 1. Threads

Содержание

Слайд 2

Concurrency A single application is often expected to do more than

Concurrency

A single application is often expected to do more than one

thing at a time
Software that can do such things is known as concurrent software
Since version 5.0, the Java platform has also included high-level concurrency APIs

*

InfopulseTraining Center

Слайд 3

Processes A process has a self-contained execution environment A process generally

Processes

A process has a self-contained execution environment
A process generally has a

complete, private set of basic run-time resources (e.g own memory space)
A Java application can create additional processes using a ProcessBuilder object.
Multiprocess applications are beyond the scope of this lesson

*

InfopulseTraining Center

Слайд 4

Threads I Threads are sometimes called lightweight processes Both processes and

Threads I

Threads are sometimes called lightweight processes
Both processes and threads provide

an execution environment, but creating a new thread requires fewer resources than creating a new process.
Threads exist within a process — every process has at least one thread

*

InfopulseTraining Center

Слайд 5

Threads II Threads share the process's resources, including memory and open

Threads II

Threads share the process's resources, including memory and open files
From

the application programmer's point of view, you start with just one thread, called the main thread
This thread has the ability to create additional threads

*

InfopulseTraining Center

Слайд 6

Defining a Thread An application that creates an instance of Thread

Defining a Thread

An application that creates an instance of Thread must

provide the code that will run in that thread:
Provide a Runnable object.
Create Thread Subclass.

*

InfopulseTraining Center

Слайд 7

Runnable Object The Runnable interface defines a single method, run, meant

Runnable Object

The Runnable interface defines a single method, run, meant to

contain the code executed in the thread
The Runnable object is passed to the Thread constructor
Thread’s start method is called

*

InfopulseTraining Center

Слайд 8

Runnable Object Example public class HelloRunnable implements Runnable { public void

Runnable Object Example

public class HelloRunnable implements Runnable {
  public void run()

{
System.out.println("Hello from a thread!");

public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();

}

*

InfopulseTraining Center

Слайд 9

Runnable Object in Java 8 public static void main(String args[]) {

Runnable Object in Java 8

public static void main(String args[]) {
Runnable

r =
() -> System.out.println("Hello world!");
new Thread(r).start();

Слайд 10

Thread Subclass The Thread class itself implements Runnable, though its run

Thread Subclass

The Thread class itself implements Runnable, though its run method

does nothing
An application can subclass Thread, providing its own implementation of run

*

InfopulseTraining Center

Слайд 11

Thread Subclass Example public class HelloThread extends Thread { public void

Thread Subclass Example

public class HelloThread extends Thread { 
public void run()

{ System.out.println("Hello from a thread!");

public static void main(String args[]) { (new HelloThread()).start();
}  
}

*

InfopulseTraining Center

Слайд 12

Runnable vs Thread Subclass A Runnable object employment is more general,

Runnable vs Thread Subclass

A Runnable object employment is more general, because

the Runnable object can subclass a class other than Thread
Thread subclassing is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread
A Runnable object is applicable to the high-level thread management APIs

*

InfopulseTraining Center

Слайд 13

Pausing Execution with Sleep Thread.sleep causes the current thread to suspend

Pausing Execution with Sleep

Thread.sleep causes the current thread to suspend execution

for a specified period
This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system
The sleep period can be terminated by interrupts

*

InfopulseTraining Center

Слайд 14

Sleep Example public class SleepMessages { public static void main(String args[])

Sleep Example

public class SleepMessages {
public static void main(String args[]) throws

InterruptedException {
String importantInfo[] = { "Mares eat oats",
"Does eat oats", "Little lambs eat ivy",
"A kid will eat ivy too"};
for (int i = 0; i < importantInfo.length; i++) {
Thread.sleep(4000);
System.out.println(importantInfo[i]);
}
}
}

*

InfopulseTraining Center

Слайд 15

Thread Race Example Create two classes: first implements Runnable interface, and

Thread Race Example

Create two classes: first implements Runnable interface, and second

extends Thread class. Method run() in both classes prints thread and iteration numbers and sleeps in some seconds.

*

InfopulseTraining Center

Слайд 16

Thread Race Example See 811ThreadRace project for the full text. * InfopulseTraining Center

Thread Race Example

See 811ThreadRace project for the full text.

*

InfopulseTraining Center

Слайд 17

Thread Terminations A thread terminates when: its run method returns, by

Thread Terminations

A thread terminates when:
its run method returns, by executing a

return statement
after executing the last statement in the method body
if an exception occurs that is not caught in the method
The interrupt method can be used to request termination of a thread

*

InfopulseTraining Center

Слайд 18

Interrupted Status When the interrupt method is called on a thread,

Interrupted Status

When the interrupt method is called on a thread, the

interrupted status of the thread is set
This is a boolean flag that is present in every thread
Each thread should occasionally check whether it has been interrupted

*

InfopulseTraining Center

Слайд 19

How to Check Interrupted Status To find out whether the interrupted

How to Check Interrupted Status

To find out whether the interrupted status

was set, first call the static Thread.currentThread method to get the current thread and then call the isInterrupted method:
while (!Thread.currentThread().isInterrupted())
{
do more work
}

*

InfopulseTraining Center

Слайд 20

InterruptedException If a thread is blocked, it cannot check the interrupted

InterruptedException

If a thread is blocked, it cannot check the interrupted status
This

is where the InterruptedException comes in
When the interrupt method is called on a thread that blocks on a call such as sleep or wait, the blocking call is terminated by an InterruptedException

*

InfopulseTraining Center

Слайд 21

InterruptedException Example for (int i = 0; i // Pause for

InterruptedException Example

for (int i = 0; i < importantInfo.length; i++)

{
// Pause for 4 seconds
try { Thread.sleep(4000); }
catch (InterruptedException e) {
return;
}
System.out.println(importantInfo[i]);
}

*

InfopulseTraining Center

Слайд 22

Joins The join method allows one thread to wait for the

Joins

The join method allows one thread to wait for the completion

of another
If t is a Thread object whose thread is currently executing, t.join() causes the current thread to pause execution until t's thread terminates
Overloads of join allow the programmer to specify a waiting period
join responds to an interrupt by exiting with an InterruptedException

*

InfopulseTraining Center

Слайд 23

Join Exercise Modify 811ThreadRace project so that first thread should wait

Join Exercise

Modify 811ThreadRace project so that first thread should wait for

second thread finishing

*

InfopulseTraining Center

Слайд 24

ThreadRace Class public static void main(String[] args) throws InterruptedException{ ThreadRunnab r

ThreadRace Class

public static void main(String[] args) throws InterruptedException{
ThreadRunnab r = new

ThreadRunnab();
Thread t1 = new Thread(r);
Thread t2 = new ThreadThread();
r.setThread(t2);
t1.start();
t2.start();
}

*

InfopulseTraining Center

Слайд 25

Join Exercise See 812ThreadJoin project for the full text. * InfopulseTraining Center

Join Exercise

See 812ThreadJoin project for the full text.

*

InfopulseTraining Center

Слайд 26

Thread Priority public final void setPriority(int newPriority) - changes the priority

Thread Priority

public final void setPriority(int newPriority) - changes the priority of this thread
public final int getPriority()

- returns this thread's priority

*

InfopulseTraining Center

Слайд 27

Sharing Resources Example Try to generate Fibonacci series in one thread

Sharing Resources Example

Try to generate Fibonacci series in one thread and

print its values in another thread

*

InfopulseTraining Center

Слайд 28

Sharing Resources Example See 813Resources project for the full text. * InfopulseTraining Center

Sharing Resources Example

See 813Resources project for the full text.

*

InfopulseTraining Center