0% found this document useful (0 votes)
5 views21 pages

10 Multithreading

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views21 pages

10 Multithreading

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

VISUAL

PROGRAMMING
Multithreading

MUSBAH J. MOUSA
IYAS A. I. ESHAIKHKHALIL

1
OUTLINES
• Introduction to Shapes
• Threads Concept
• Creating Tasks and Threads
• The Thread Class
• The static sleep method.
• The Thread join, isAlive, interrupt, and isInterrupted
methods
• Thread Safety
• Modifying JavaFX Objects from another Thread
• When to Use Threads in Our Applications
• Long-Running Tasks Types

2
INTRODUCTION
• Multithreading is like having multiple tasks happening
simultaneously.
• It allows a program to do multiple things at the same time,
such as performing calculations while listening for user
input.
• Think of it as a way to efficiently handle different tasks
concurrently, making your program more responsive and
efficient.

3
Threads Concept

Multiple
threads on
multiple
CPUs

Multiple
threads
sharing a
single CPU

4
Creating Tasks and Threads
In Java, you can introduce parallel execution in your application
by creating a new thread.
This is achieved by instantiating a new object from the Thread
class and then invoking the start method on that object.

Thread thread = new Thread(/* Runnable object */);


thread.start();

5
RUNNABLE
• The java.lang.Runnable interface is designed to be
implemented by a class whose instances are meant to be
executed by a thread.
• Runnable interface is a SAM (Single Abstract Method)
interface.
• It contains only the run abstract method.
• The run method implemented in a concrete class functionality
is similar to the main method in Java applications. It serves as
the main method for the new thread.

6
Creating Tasks and Threads

7
EXAMPLE:
Using the Runnable 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.

TaskThreadDemo

8
THE THREAD CLASS

9
THE STATIC
SLEEP(MILLISECONDS) METHOD
• The sleep(long mills) method puts the thread to sleep for the
specified time in milliseconds.
• Example:
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
try {
if (i >= 50) Thread.sleep(1);
}
catch (InterruptedException ex) {
}
}
}

• Every time a number (>= 50) is printed, the thread is put to sleep
for 1 millisecond.

10
THE JOIN() METHOD
You can use the join() method to force one thread to wait for
another thread to finish.
Example:
public void run() { Thread Thread
Thread thread4 = new Thread( print100 printA
new PrintChar('c', 40));
thread4.start(); -char token -char token
try {
+getToken +getToken
for (int i = 1; i <= lastNum; i++) { printA.join()
+setToken +setToken
System.out.print(" " + i); +paintCompo +paintCompo
if (i == 50) thread4.join(); Wait for printA
-char
net token net
} to finish+mouseClicke +mouseClicke
} +getToken
d d
catch (InterruptedException ex) { +getToken +setToken printA finished
} +setToken +paintCompone
t
+paintComponet -char token
} +mouseClicked
The numbers after 50 are printed after thread thread4 is finished.

11
isAlive(), interrupt(), and
isInterrupted()
• The isAlive() method is used to find out the state of a thread.
• It returns true if a thread is in the Ready, Blocked, or
Running state; it returns false if a thread is new and has
not started or if it is finished.
• The interrupt() method interrupts a thread in the following
way:
• If a thread is currently in the Ready or Running state, its
interrupted flag is set; if a thread is currently blocked, it is
awakened and enters the Ready state, and an
java.io.InterruptedException is thrown.

• The isInterrupt() method tests whether the thread is


interrupted.

12
THREAD SAFETY
• Although multithreading is a powerful feature, it comes at a
price.
• In multithreaded environments, we need to write
implementations in a thread-safe way.
• This means that different threads can access the same
resources without exposing erroneous behavior or producing
unpredictable results.
• This programming methodology is known as “thread-safety.”

13
THREAD SAFETY EXAMPLE
Counter
private static class Counter{
private int count = 0;

public void increment(){


count++;
}

public int getCount(){


return count;
}
}

14
THREAD SAFETY EXAMPLE
ThreadSafety
Counter i = new Counter();
Thread t1 = new Thread(() -> {
int c1 = 0;
for (; i.getCount() < 10; i.increment()) {
System.out.println(Thread.currentThread().getName()+ ", Count = "
+ i.getCount());
c1++;
}
System.out.println(Thread.currentThread().getName()+ ", Looped = "
+ c1);
});

15
THREAD SAFETY EXAMPLE
ThreadSafety
Thread t2 = new Thread(() -> {
int c2 = 0;
for (; i.getCount() < 10; i.increment()) {
System.out.println(Thread.currentThread().getName()+ ", Count = " +
i.getCount());
c2++;
}
System.out.println(Thread.currentThread().getName()+ ", Looped = " + c2);
});
t1.start();
t2.start();

16
JavaFX Thread
• JavaFX creates an application thread for running the
application start method, processing input events, and
running animation timelines.
• Creation of JavaFX Scene and Stage objects as well as
modification of scene graph operations to live objects (those
objects already attached to a scene) must be done on the
JavaFX application thread.

17
Modifying JavaFX Objects
from another Thread
• When you want to create or modify any JavaFX object you
must invoke the runLater method.
• Invoking Platform.runLater(Runnable r) tells the system to
run this Runnable object in the application thread.

18
When to Use Threads in Our
Applications
• JavaFX operates on a single thread responsible for creating
and modifying objects, handling input events, and managing
animations, as we previously mentioned.
• When long-running tasks are performed on the application
thread, it can cause the thread to become unresponsive or
hang.

19
Long-Running Tasks
Types
• File I/O Operations: Reading or writing large files can be a time-
consuming task.
• Database Operations: Querying or updating a database, especially
when dealing with a large amount of data, can take a significant
amount of time.
• Image Processing: Performing complex image processing tasks,
such as applying filters or performing transformations, can be
computationally intensive and time-consuming.
• Network Operations: Making HTTP requests, downloading files, or
interacting with remote APIs can introduce delays due to network
latency.
• Complex Calculations: Performing complex calculations or
simulations that require substantial computation time can benefit
from running in background threads.

20
ANY QUESTIONS?

21

You might also like