SlideShare a Scribd company logo
Module 08 – Java Threading
Danairat T.
Line ID: Danairat
FB: Danairat Thanabodithammachari
+668-1559-1446
Fundamental Java Programming
The Course Outline
Module 01 – Introduction to Java
Module 02 – Basic Java Programming
Module 03 – Control Flow and Exception Handling
Module 04 – Object Oriented in Java
Module 05 – Java Package and Access Control
Module 06 – Java File IO
Module 07 – Java Networking
Module 08 – Java Threading
Module 08 – Java Threading
‱ Processes
‱ Threads
‱ Java main method as a starting thread
‱ Creating Thread with extending Thread class
‱ Creating Thread with implementing Runnable interface
‱ Java Thread Priority
‱ Network Server Thread Programming
Processes
A process has a self-contained execution environment.
A process generally has a complete, private set of
basic run-time resources; in particular, each process
has its own memory space.
Processes are often seen as synonymous with
programs or applications. However, what the user sees
as a single application may in fact be a set of
cooperating processes. To facilitate communication
between processes, most operating systems support
Inter Process Communication (IPC) resources, such as
pipes and sockets.
Threads
Multithreaded execution is an essential feature of
the Java platform. Every application has at least
one thread. 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.
Eg. Two Threads are running in
a single core processor
Java main method as a starting thread
class TypicalClass {
public void aMethod() {
System.out.println(Thread.currentThread());
}
public static void main(String[] args) {
// main() is run in a single thread
System.out.println(Thread.currentThread());
TypicalClass hWorld = new TypicalClass();
hWorld.aMethod();
}
} Thread[main,5,main]
Thread[main,5,main]
Defining and Starting a Thread
1.) Runnable Interface. 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,
public class HelloRunnable implements Runnable {
public void run() {
System.out.println(Thread.currentThread());
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
System.out.println(Thread.currentThread());
(new Thread(new HelloRunnable())).start();
}
}
Thread[main,5,main]
Thread[Thread-0,5,main]
Hello from a thread!
Defining and Starting a Thread
2.) Subclass Thread. The Thread class itself implements
Runnable, though its run method does nothing. An application
can subclass Thread, providing its own implementation of run,
public class HelloThread extends Thread {
public void run() {
System.out.println(Thread.currentThread());
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
System.out.println(Thread.currentThread());
(new HelloThread()).start();
}
}
Thread[main,5,main]
Thread[Thread-0,5,main]
Hello from a thread!
Thread Priority
package BasicThread;
public class ThreadPriorityDemo extends Thread{
ThreadPriorityDemo(String name) {
super(name);
}
public void run() {
for (int i = 0; i<100; i++) System.out.print(getName());
}
public static void main(String args[]) {
ThreadPriorityDemo t01 = new ThreadPriorityDemo("T01");
ThreadPriorityDemo t02 = new ThreadPriorityDemo("T02");
t01.start();
t02.start();
t02.setPriority(10); // 1 min, 5 default, 10 max
}
}
Network Server Thread Programming
import java.io.*;
import java.net.*;
public class MyServerThread extends Thread {
ServerSocket s;
public MyServerThread() throws Exception {
super();
// Register service on port 1234
s = new ServerSocket(1234);
}
public void run() {
try {
while (true) {
Socket s1 = s.accept(); // Wait and accept a connection
// Read input from client
ObjectInputStream objInputStream = new
ObjectInputStream(s1.getInputStream());
Customer cust1 = (Customer)objInputStream.readObject();
cust1.setCollectedPoints(3000); // Dummy result
// Write result to client
OutputStream s1out = s1.getOutputStream();
ObjectOutputStream objOutputStream = new
ObjectOutputStream(s1out);
objOutputStream.writeObject(cust1);
// Close the connection, but not the server socket
objOutputStream.close();
s1out.close();
objInputStream.close();
s1.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
MyServerThread myServerThread = new MyServerThread();
myServerThread.start();
}
}
Client Test
import java.net.*;
import java.io.*;
public class MyClient2 {
public static void main(String[] args) throws Exception {
// Open your connection to a server, at port 1234
Socket s1 = new Socket("127.0.0.1", 1234);
// Write object to the socket server
Customer cust1 = new Customer();
cust1.setName("Somchai");
ObjectOutputStream objOutputStream =
new ObjectOutputStream(s1.getOutputStream());
objOutputStream.writeObject(cust1);
// Get result from server
InputStream s1In = s1.getInputStream();
ObjectInputStream objInputStream = new
ObjectInputStream(s1In);
Customer custResult =
(Customer)objInputStream.readObject();
System.out.println(custResult.getName() + " has " +
custResult.getCollectedPoints() + " points");
// When done, just close the connection and exit
objInputStream.close();
s1In.close();
objOutputStream.close();
s1.close();
}
}
Supported Class – Customer Data Object
import java.io.Serializable;
public class Customer implements Serializable{
private String name;
private int collectedPoints;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCollectedPoints(int
collectedPoints) {
this.collectedPoints = collectedPoints;
}
public int getCollectedPoints() {
return collectedPoints;
}
}
Danairat T.
Line ID: Danairat
FB: Danairat Thanabodithammachari
+668-1559-1446
Thank you

More Related Content

PPT
Hibernate
PPS
Advance Java
PDF
Java Programming - 01 intro to java
PPTX
Java servlets
PPT
æŻ”XMLæ›Žć„œç”šçš„Java Annotation
PPT
Java RMI
PPTX
Spring data jpa
ODP
Spring 4 advanced final_xtr_presentation
Hibernate
Advance Java
Java Programming - 01 intro to java
Java servlets
æŻ”XMLæ›Žć„œç”šçš„Java Annotation
Java RMI
Spring data jpa
Spring 4 advanced final_xtr_presentation

What's hot (20)

PPTX
Database connect
PDF
Ejb3 Dan Hinojosa
PPTX
JDBC - JPA - Spring Data
PPT
Jsp/Servlet
PPTX
Java Servlet
PPTX
JSP- JAVA SERVER PAGES
ODP
Spring 4 final xtr_presentation
PDF
Java EE 與 é›Čç«Żé‹çź—çš„ć±•æœ›
PPT
Tech talk
PPT
Java jdbc
PPS
Java rmi example program with code
PDF
Chat Room System using Java Swing
PPT
ExtJs Basic Part-1
ODP
Creating a Java EE 7 Websocket Chat Application
PPT
Servlet life cycle
PDF
Lecture 3: Servlets - Session Management
PPTX
java script
PPT
Deployment
PDF
Simple Jdbc With Spring 2.5
PPT
JavaScript
Database connect
Ejb3 Dan Hinojosa
JDBC - JPA - Spring Data
Jsp/Servlet
Java Servlet
JSP- JAVA SERVER PAGES
Spring 4 final xtr_presentation
Java EE 與 é›Čç«Żé‹çź—çš„ć±•æœ›
Tech talk
Java jdbc
Java rmi example program with code
Chat Room System using Java Swing
ExtJs Basic Part-1
Creating a Java EE 7 Websocket Chat Application
Servlet life cycle
Lecture 3: Servlets - Session Management
java script
Deployment
Simple Jdbc With Spring 2.5
JavaScript
Ad

Viewers also liked (18)

PDF
Manga Kissxsis tomo 10
 
PPTX
HIV diagnoses in children and adolescents: key issues in Europe and different...
PDF
Oncotarget OlgaÂŽs paper
PDF
Design thinking bbva
PPT
G16 osteoporotic fxs
PPT
PREVENTION AND PROTECTION OF A HIP FRACTURES
PDF
Reserve en lĂ­nea una empresa para asear su casa u oficina sin preocupaciones
PDF
ÂżCuĂĄles son las estrategias de polĂ­tica pĂșblica que impulsan la economĂ­a digi...
PPTX
Guidance on programmatic management of latent TB infection: applicability for...
PPTX
Receta de cocina, tarta de chocolate y galletas
PPTX
Digital cash, near feild communication and ultra cash
PPTX
Receta de cocina pastel victoria
PDF
Catalejos.cc
PPTX
Antibiotic associated diarrhea
PPT
Role of a Forensic Investigator
PDF
Tendencias y oportunidades TIC para las organizaciones en 2016
PDF
foldercv
PPT
sewing tools and equipments
Manga Kissxsis tomo 10
 
HIV diagnoses in children and adolescents: key issues in Europe and different...
Oncotarget OlgaÂŽs paper
Design thinking bbva
G16 osteoporotic fxs
PREVENTION AND PROTECTION OF A HIP FRACTURES
Reserve en lĂ­nea una empresa para asear su casa u oficina sin preocupaciones
ÂżCuĂĄles son las estrategias de polĂ­tica pĂșblica que impulsan la economĂ­a digi...
Guidance on programmatic management of latent TB infection: applicability for...
Receta de cocina, tarta de chocolate y galletas
Digital cash, near feild communication and ultra cash
Receta de cocina pastel victoria
Catalejos.cc
Antibiotic associated diarrhea
Role of a Forensic Investigator
Tendencias y oportunidades TIC para las organizaciones en 2016
foldercv
sewing tools and equipments
Ad

Similar to Java Programming - 08 java threading (20)

PPTX
advanced java ppt
PPT
web programming-Multithreading concept in Java.ppt
PPT
Java Performance, Threading and Concurrent Data Structures
PPT
Md09 multithreading
DOCX
Threadnotes
PDF
Lecture10
PPTX
PPTX
Multithreading.pptx
PDF
Concurrency in java
PPT
Threads in java, Multitasking and Multithreading
PPTX
multithreading.pptx
PPT
Java multi threading
PPT
Threads in Java
PPTX
Multithreading.pptx
PPTX
U4 JAVA.pptx
PPTX
Java Multithreading - how to create threads
PPTX
Lecture 23-24.pptx
PPTX
Multithreading
PPTX
Multithreading
PPTX
Object-Oriented-Prog_MultiThreading.pptx
advanced java ppt
web programming-Multithreading concept in Java.ppt
Java Performance, Threading and Concurrent Data Structures
Md09 multithreading
Threadnotes
Lecture10
Multithreading.pptx
Concurrency in java
Threads in java, Multitasking and Multithreading
multithreading.pptx
Java multi threading
Threads in Java
Multithreading.pptx
U4 JAVA.pptx
Java Multithreading - how to create threads
Lecture 23-24.pptx
Multithreading
Multithreading
Object-Oriented-Prog_MultiThreading.pptx

More from Danairat Thanabodithammachari (20)

PDF
Thailand State Enterprise - Business Architecture and SE-AM
PDF
Agile Management
PDF
Agile Organization and Enterprise Architecture v1129 Danairat
PDF
Blockchain for Management
PDF
Enterprise Architecture and Agile Organization Management v1076 Danairat
PDF
Agile Enterprise Architecture - Danairat
PDF
Digital Transformation, Enterprise Architecture, Big Data by Danairat
PDF
Big data Hadoop Analytic and Data warehouse comparison guide
PDF
Big data hadooop analytic and data warehouse comparison guide
PDF
Perl for System Automation - 01 Advanced File Processing
PDF
Perl Programming - 04 Programming Database
PDF
Perl Programming - 03 Programming File
PDF
Perl Programming - 02 Regular Expression
PDF
Perl Programming - 01 Basic Perl
PDF
Setting up Hadoop YARN Clustering
PDF
JEE Programming - 03 Model View Controller
PDF
JEE Programming - 05 JSP
PDF
JEE Programming - 04 Java Servlets
PDF
JEE Programming - 08 Enterprise Application Deployment
PDF
JEE Programming - 07 EJB Programming
Thailand State Enterprise - Business Architecture and SE-AM
Agile Management
Agile Organization and Enterprise Architecture v1129 Danairat
Blockchain for Management
Enterprise Architecture and Agile Organization Management v1076 Danairat
Agile Enterprise Architecture - Danairat
Digital Transformation, Enterprise Architecture, Big Data by Danairat
Big data Hadoop Analytic and Data warehouse comparison guide
Big data hadooop analytic and data warehouse comparison guide
Perl for System Automation - 01 Advanced File Processing
Perl Programming - 04 Programming Database
Perl Programming - 03 Programming File
Perl Programming - 02 Regular Expression
Perl Programming - 01 Basic Perl
Setting up Hadoop YARN Clustering
JEE Programming - 03 Model View Controller
JEE Programming - 05 JSP
JEE Programming - 04 Java Servlets
JEE Programming - 08 Enterprise Application Deployment
JEE Programming - 07 EJB Programming

Recently uploaded (20)

PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
 
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
top salesforce developer skills in 2025.pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Digital Strategies for Manufacturing Companies
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
System and Network Administraation Chapter 3
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
Design an Analysis of Algorithms II-SECS-1021-03
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
 
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Wondershare Filmora 15 Crack With Activation Key [2025
top salesforce developer skills in 2025.pdf
Operating system designcfffgfgggggggvggggggggg
Odoo Companies in India – Driving Business Transformation.pdf
VVF-Customer-Presentation2025-Ver1.9.pptx
Digital Strategies for Manufacturing Companies
Which alternative to Crystal Reports is best for small or large businesses.pdf
ManageIQ - Sprint 268 Review - Slide Deck
CHAPTER 2 - PM Management and IT Context
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
System and Network Administraation Chapter 3
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Online Work Permit System for Fast Permit Processing
Design an Analysis of Algorithms I-SECS-1021-03
PTS Company Brochure 2025 (1).pdf.......
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
How to Choose the Right IT Partner for Your Business in Malaysia

Java Programming - 08 java threading

  • 1. Module 08 – Java Threading Danairat T. Line ID: Danairat FB: Danairat Thanabodithammachari +668-1559-1446
  • 2. Fundamental Java Programming The Course Outline Module 01 – Introduction to Java Module 02 – Basic Java Programming Module 03 – Control Flow and Exception Handling Module 04 – Object Oriented in Java Module 05 – Java Package and Access Control Module 06 – Java File IO Module 07 – Java Networking Module 08 – Java Threading
  • 3. Module 08 – Java Threading ‱ Processes ‱ Threads ‱ Java main method as a starting thread ‱ Creating Thread with extending Thread class ‱ Creating Thread with implementing Runnable interface ‱ Java Thread Priority ‱ Network Server Thread Programming
  • 4. Processes A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. Processes are often seen as synonymous with programs or applications. However, what the user sees as a single application may in fact be a set of cooperating processes. To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets.
  • 5. Threads Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread. 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. Eg. Two Threads are running in a single core processor
  • 6. Java main method as a starting thread class TypicalClass { public void aMethod() { System.out.println(Thread.currentThread()); } public static void main(String[] args) { // main() is run in a single thread System.out.println(Thread.currentThread()); TypicalClass hWorld = new TypicalClass(); hWorld.aMethod(); } } Thread[main,5,main] Thread[main,5,main]
  • 7. Defining and Starting a Thread 1.) Runnable Interface. 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, public class HelloRunnable implements Runnable { public void run() { System.out.println(Thread.currentThread()); System.out.println("Hello from a thread!"); } public static void main(String args[]) { System.out.println(Thread.currentThread()); (new Thread(new HelloRunnable())).start(); } } Thread[main,5,main] Thread[Thread-0,5,main] Hello from a thread!
  • 8. Defining and Starting a Thread 2.) Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, public class HelloThread extends Thread { public void run() { System.out.println(Thread.currentThread()); System.out.println("Hello from a thread!"); } public static void main(String args[]) { System.out.println(Thread.currentThread()); (new HelloThread()).start(); } } Thread[main,5,main] Thread[Thread-0,5,main] Hello from a thread!
  • 9. Thread Priority package BasicThread; public class ThreadPriorityDemo extends Thread{ ThreadPriorityDemo(String name) { super(name); } public void run() { for (int i = 0; i<100; i++) System.out.print(getName()); } public static void main(String args[]) { ThreadPriorityDemo t01 = new ThreadPriorityDemo("T01"); ThreadPriorityDemo t02 = new ThreadPriorityDemo("T02"); t01.start(); t02.start(); t02.setPriority(10); // 1 min, 5 default, 10 max } }
  • 10. Network Server Thread Programming import java.io.*; import java.net.*; public class MyServerThread extends Thread { ServerSocket s; public MyServerThread() throws Exception { super(); // Register service on port 1234 s = new ServerSocket(1234); } public void run() { try { while (true) { Socket s1 = s.accept(); // Wait and accept a connection // Read input from client ObjectInputStream objInputStream = new ObjectInputStream(s1.getInputStream()); Customer cust1 = (Customer)objInputStream.readObject(); cust1.setCollectedPoints(3000); // Dummy result // Write result to client OutputStream s1out = s1.getOutputStream(); ObjectOutputStream objOutputStream = new ObjectOutputStream(s1out); objOutputStream.writeObject(cust1); // Close the connection, but not the server socket objOutputStream.close(); s1out.close(); objInputStream.close(); s1.close(); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { MyServerThread myServerThread = new MyServerThread(); myServerThread.start(); } }
  • 11. Client Test import java.net.*; import java.io.*; public class MyClient2 { public static void main(String[] args) throws Exception { // Open your connection to a server, at port 1234 Socket s1 = new Socket("127.0.0.1", 1234); // Write object to the socket server Customer cust1 = new Customer(); cust1.setName("Somchai"); ObjectOutputStream objOutputStream = new ObjectOutputStream(s1.getOutputStream()); objOutputStream.writeObject(cust1); // Get result from server InputStream s1In = s1.getInputStream(); ObjectInputStream objInputStream = new ObjectInputStream(s1In); Customer custResult = (Customer)objInputStream.readObject(); System.out.println(custResult.getName() + " has " + custResult.getCollectedPoints() + " points"); // When done, just close the connection and exit objInputStream.close(); s1In.close(); objOutputStream.close(); s1.close(); } }
  • 12. Supported Class – Customer Data Object import java.io.Serializable; public class Customer implements Serializable{ private String name; private int collectedPoints; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setCollectedPoints(int collectedPoints) { this.collectedPoints = collectedPoints; } public int getCollectedPoints() { return collectedPoints; } }
  • 13. Danairat T. Line ID: Danairat FB: Danairat Thanabodithammachari +668-1559-1446 Thank you