5.CoreJavaProgramming Day5
5.CoreJavaProgramming Day5
PROGRAMMING
AN INTRODUCTION TO JAVA
Presented By
Dr. Eman Hesham, DBA.
Agenda
A. The History and Evolution of Java
B. An Overview of Java
C. Data Types, Variables and Arrays
D. Operators, Control Statements and String Handling
E. Modifiers, Access Specifiers, Packages and Interfaces
F. Wrapper Classes, Autoboxing and Inner Classes
G. Exception Handling
H. Generics and Lambda Expressions and Method Reference
I. Java Stream API
J. Java Collections
K. Multi-Threading in Java
Lesson 11
Multi-Threading in Java
Create Simple GUI – java Swing Frame
JFrame class has various methods which can be used to customize it.
Create Simple GUI – java Swing Frame
Create Simple GUI – java Swing Panel
JPanel, a part of the Java Swing package, is a container that can store a group of
components.
The main task of JPanel is to organize components, various layouts can be set in
JPanel which provide better organization of components.
Create Simple GUI – java Swing Panel
1
Create Simple GUI
2
Multi-
Threading
What is Thread?
A Thread is
A single sequential execution path in a program
Used when we need to execute two or more program segments concurrently (multitasking).
Used in many applications:
Games, animation, perform I/O
Every program has at least two threads.
Each thread has its own stack, priority & virtual set of registers.
Multiple threads does not mean that they execute in parallel when you’re working in a single
CPU.
Some kind of scheduling algorithm is used to manage the threads (e.g. Round Robin).
The scheduling algorithm is JVM specific (i.e. depending on the scheduling algorithm of the
underlying operating system)
Threads
several thread objects that are executing concurrently:
Main Thread
Garbage
Collection th1
Event Dispatcher
Thread Thread
th2 run()
th3
run()
run()
Only one thread is executing at a time, while the others are waiting for their turn.
The task that the thread carries out is written inside the run() method.
The Thread Class
Class Thread
start()
run()
sleep()*
suspend()*
resume()*
stop()*
Working with Threads
Thread
There are two ways to work with threads:
1
public class MyThread extends Thread
start()
{
run() { }
public void run() 2 …
{ • in main() or any method:
… //write the job here
MyThread
}
} public void anyMethod()
{
MyThread th = new MyThread(); 3.a run() {
th.start(); 3.
b
…………
}
}
Working with Threads
1 void run();
class MyTask implements Runnable
{
public void run() 2
MyTask Thread
{
… //write the job here void run(){
} 3 ……… Thread()
public void anyMethod() } Thread(Runnable r)
} start()
{
run() { }
MyTask task = new MyTask(); a
Thread th = new Thread(task); b
th.start(); c
} • in main() or any method
Extending Thread VS. Implementing Runnable
your App.