Что такое findslide.org?

FindSlide.org - это сайт презентаций, докладов, шаблонов в формате PowerPoint.


Для правообладателей

Обратная связь

Email: Нажмите что бы посмотреть 

Яндекс.Метрика

Презентация на тему 8. Java concurrency 1. Threads

Содержание

ConcurrencyA single application is often expected to do more than one thing at a timeSoftware that can do such things is known as concurrent softwareSince version 5.0, the Java platform has also included high-level concurrency APIs*InfopulseTraining
8. Concurrency1. Threads ConcurrencyA single application is often expected to do more than one thing ProcessesA process has a self-contained execution environmentA process generally has a complete, Threads IThreads are sometimes called lightweight processesBoth processes and threads provide an Threads IIThreads share the process's resources, including memory and open filesFrom the Defining a ThreadAn application that creates an instance of Thread must provide Runnable ObjectThe Runnable interface defines a single method, run, meant to contain Runnable Object Examplepublic class HelloRunnable implements Runnable {   public void run() Runnable Object in Java 8public static void main(String args[]) { 	Runnable r Thread SubclassThe Thread class itself implements Runnable, though its run method does Thread Subclass Examplepublic class HelloThread extends Thread {   	public void run() Runnable vs Thread SubclassA Runnable object employment is more general, because the Pausing Execution with SleepThread.sleep causes the current thread to suspend execution for Sleep Examplepublic class SleepMessages {  	public static void main(String args[]) throws Thread Race ExampleCreate two classes: first implements Runnable interface, and second extends Thread Race ExampleSee 811ThreadRace project for the full text.*InfopulseTraining Center Thread TerminationsA thread terminates when:its run method returns, by executing a return Interrupted StatusWhen the interrupt method is called on a thread, the interrupted How to Check Interrupted StatusTo find out whether the interrupted status was InterruptedExceptionIf a thread is blocked, it cannot check the interrupted statusThis is InterruptedException Examplefor (int i = 0; i < importantInfo.length; i++) { JoinsThe join method allows one thread to wait for the completion of Join ExerciseModify 811ThreadRace project so that first thread should wait for second thread finishing*InfopulseTraining Center ThreadRace Classpublic static void main(String[] args) throws InterruptedException{		ThreadRunnab r = new ThreadRunnab();		Thread Join ExerciseSee 812ThreadJoin project for the full text.*InfopulseTraining Center Thread Prioritypublic final void setPriority(int newPriority) - changes the priority of this threadpublic final int getPriority() - Sharing Resources ExampleTry to generate Fibonacci series in one thread and print Sharing Resources ExampleSee 813Resources project for the full text.*InfopulseTraining Center Manualshttp://docs.oracle.com/javase/tutorial/essential/concurrency/index.html*InfopulseTraining Center
Слайды презентации

Слайд 2 Concurrency
A single application is often expected to do

ConcurrencyA single application is often expected to do more than one

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

ProcessesA process has a self-contained execution environmentA process generally has a

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

Threads IThreads are sometimes called lightweight processesBoth processes and threads provide

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

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

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

Defining a ThreadAn application that creates an instance of Thread must

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,

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

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 {
 

Runnable Object Examplepublic class HelloRunnable implements Runnable {  public void run()

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

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

args[]) {
Runnable r =
() -> System.out.println("Hello world!");


new Thread(r).start();



Слайд 10 Thread Subclass
The Thread class itself implements Runnable, though

Thread SubclassThe Thread class itself implements Runnable, though its run method

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 { 

Thread Subclass Examplepublic class HelloThread extends Thread {  	public void run()


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

Runnable vs Thread SubclassA Runnable object employment is more general, because

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

Pausing Execution with SleepThread.sleep causes the current thread to suspend execution

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

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

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

Thread Race ExampleCreate two classes: first implements Runnable interface, and second

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

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

text.

*
InfopulseTraining Center


Слайд 17 Thread Terminations
A thread terminates when:
its run method returns,

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

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

Interrupted StatusWhen the interrupt method is called on a thread, the

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

How to Check Interrupted StatusTo find out whether the interrupted status

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

InterruptedExceptionIf a thread is blocked, it cannot check the interrupted statusThis

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

InterruptedException Examplefor (int i = 0; i < importantInfo.length; 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

JoinsThe join method allows one thread to wait for the completion

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

Join ExerciseModify 811ThreadRace project so that first thread should wait for second thread finishing*InfopulseTraining Center

should wait for second thread finishing
*
InfopulseTraining Center


Слайд 24 ThreadRace Class
public static void main(String[] args) throws InterruptedException{
ThreadRunnab

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

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

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

Center


Слайд 26 Thread Priority
public final void setPriority(int newPriority) - changes the priority of

Thread Prioritypublic final void setPriority(int newPriority) - changes the priority of this threadpublic final int getPriority()

this thread
public final int getPriority() - returns this thread's priority


*
InfopulseTraining Center


Слайд 27 Sharing Resources Example
Try to generate Fibonacci series in

Sharing Resources ExampleTry to generate Fibonacci series in one thread and

one thread and print its values in another thread


*

InfopulseTraining Center


Слайд 28 Sharing Resources Example
See 813Resources project for the full

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

text.

*
InfopulseTraining Center


  • Имя файла: 8-java-concurrency-1-threads.pptx
  • Количество просмотров: 124
  • Количество скачиваний: 0