0% found this document useful (0 votes)
2 views94 pages

Unit 5 Multithreading in Java

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)
2 views94 pages

Unit 5 Multithreading in Java

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/ 94

SNJB’s Late Sau. K. B. J.

College of Engineering
Unit 5
Multithreading in Java

Concurrency and Synchronization, Java Thread Model: Thread priorities,


Synchronization, Messaging, Main Thread, Creating thread: Implementing
Thread using thread class and Runnable interface. Creating multiple threads
using isAlive() and join()
Web Based Application in Java: Use of JavaScript for creating web based
applications in java, Introduction to javascript frameworks- React, Vue,
Angular

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Application of Multithreading

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

● A program with multiple threads running within a single


instance could be considered as a multitasking system within
an OS.
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

By extending Thread class :


•Create a class that extends Thread class.
• Create instance of that class.
• The class which extends Thread class must override the
run( ) method of Thread class.
• It must call start( ) to begin execution of new thread.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Create Thread by Extending Thread Class

class Create extends Thread Thread.sleep(500);


{ } //for close
Create() }catch(InterruptedException e){ }
{ System.out.println("Child Exiting");
super("ABC"); } //run() close
start(); public static void main(String[] args)
}// Constructor Closed
{
public void run() Create c = new Create();
{ try {
try { for(int i = 0;i<5;i++)
{ System.out.println("Mainthread"+i);
for(int i = 0;i<5;i++)
Thread.sleep(1000);
{ System.out.println("Child : " +i); } //for close
}catch(InterruptedException e) { }
System.out.println("Main Exiting");
} }
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Create Thread by Extending Thread Class..Output

Child : 0
Mainthread0
Child : 1
Mainthread1
Child : 2
Child : 3
Mainthread2
Child : 4
Child Exiting
Mainthread3
Mainthread4
Main Exiting
...Program finished with exit code 0
Press ENTER to exit console.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Create Thread by Implemented Runnable

class Create implements Runnable { Thread.sleep(500);


Thread t; } //for close
Create() }catch(InterruptedException e){ }
{ System.out.println("Child Exiting");
t = new } //run() close
Thread(this,”DemoThread”); public static void main(String[] args)
t.start();
{
}// Constructor Closed Create c = new Create();
public void run() try {
{ for(int i = 0;i<5;i++)
try { { System.out.println("Mainthread"+i);
Thread.sleep(1000);
for(int i = 0;i<5;i++) } //for close
{ System.out.println("Child : " +i); }catch(InterruptedException e) { }
System.out.println("Main Exiting");
} }
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Key Thread Runnable
Basic Thread is a class. It is used to create Runnable is a functional
a thread interface which is used to
create a thread
Methods It has multiple methods including It has only abstract method
start() and run() run()
Each thread creates a unique object Multiple threads share the
and gets associated with it same objects.

Memory More memory required Less memory required

Limitatio Multiple Inheritance is not allowed in If a class is implementing the


n java hence after a class extends runnable interface then your
Thread class, it can not extend any class can extend another
other class class.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Thread Methods

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Main Thread

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Main Thread

The general form of currentThread method is :


static Thread currentThread();
Hence it can be invoked as follows :
Thread.currentThread();
For Ex :

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Main Thread
class Demo
{
public static void main(String args[])
{
Thread t = Thread.currentThread( );
System.out.println(“The Thread is : “ +t);
}
}
O/p : The Thread is : Thread[main,5,main]

In the output Thread[main,5,main] : The order is :

[Name of thread , Priority of thread , & Group of thread]

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Main Thread
class Demo
OUTPUT
{
public static void main(String args[]) The Thread is :
{ Thread[main,5,main]
Thread t = Thread.currentThread( ); The new name is : [First
System.out.println(“The Thread is : “ +t); Thread,5,main]
t.setName(“First Thread”);
The Thread priority is : 5
System.out.println(“The new name is : “ +t); The new priority is : 10
int p = t.getPriority( );
System.out.println(“The Thread priority is : “ +p);
t.setPriority(10);
System.out.println(“The new priority is : “ +t.getPriority( ));

}
}
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple Threads
// Using join() to wait for threads to finish. public void run()
class N implements Runnable {
{ try
String name; // name of thread {
Thread t; for(int i = 5; i > 0; i--)
N(String tName) {
{ System.out.println(name + ": " + i);
name = tName; Thread.sleep(1000);
t = new Thread(this, name); }
System.out.println("New thread: " + t); } catch (InterruptedException e) {
t.start(); // Start the thread System.out.println(name + " interrupted.");
} } //catch close()
// This is the entry point for thread. System.out.println(name + " exiting.");
}
}

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Multiple Threads
class DemoJoin // wait for threads to finish
{ try
public static void main(String args[]) {
{ System.out.println("Waiting for threads to
N ob1 = new N("One"); finish.");
N ob2 = new N("Two"); ob1.t.join();
ob2.t.join();
N ob3 = new N("Three");
ob3.t.join();
System.out.println("Thread One is alive: "+
}
ob1.t.isAlive()); catch (InterruptedException e)
System.out.println("Thread Two is alive: "+
{
ob2.t.isAlive()); System.out.println("Main thread Interrupted");
System.out.println("Thread Three is alive: "+
}
ob3.t.isAlive()); System.out.println("One is alive: "+
ob1.t.isAlive());
System.out.println("Two is alive: "+
ob2.t.isAlive());
System.out.println("Threeisalive: "+
ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
Department of Computer
} Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple Threads ..Output
SamYour output may vary based on processor speed and task load

New thread: Thread[One,5,main]


New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Problem without
class Table{

void printTable(int n){


Synchronization
//method not synchronized

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{

Thread.sleep(400);

}catch(Exception e){System.out.println(e);}

} //for close

} } Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Problem without
class MyThread1 extends Thread{ class MyThread2 extends Thread{

Table t;
Synchronization..>Contd
Table t;

MyThread1(Table t){ MyThread2(Table t){

this.t=t; this.t=t;

} }

public void run(){ public void run(){

t.printTable(5); t.printTable(100);

} }

} }

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Problem without
class TestSynchronization1{
Synchronization..>Contd
public static void main(String args[]){
OUTPUT
5
100
Table obj = new Table();//only one object 10
MyThread1 t1=new MyThread1(obj); 200
15
MyThread2 t2=new MyThread2(obj);
300
t1.start(); 20
400
t2.start();
25
} 500
}

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Synchronization
class Table{

synchronized void printTable(int n){

//method not synchronized

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{

Thread.sleep(400);

}catch(Exception e){System.out.println(e);}

} //for close

} } Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Synchronization..>Contd
class MyThread1 extends Thread{ class MyThread2 extends Thread{

Table t; Table t;

MyThread1(Table t){ MyThread2(Table t){

this.t=t; this.t=t;

} }

public void run(){ public void run(){

t.printTable(5); t.printTable(100);

} }

} }

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Synchronization…Contd
class TestSynchronization1{ OUTPUT
public static void main(String args[]){ 5
10
Table obj = new Table();//only one object 15
MyThread1 t1=new MyThread1(obj); 20
25
MyThread2 t2=new MyThread2(obj);
100
t1.start(); 200
300
t2.start();
400
} 500
}

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

wait() join()

It is a method of java.lang.Object class. It is a method of java.lang.Thread

wait() method can be called by a


It is used to stop the current thread.
synchronized block or method.

wait() method is implemented for It can be called either with synchronized


performing multi-thread-synchronization. and without synchronized context.

Its syntax is -: Its syntax is -:


public final void wait() throws public final void join() throws
InterruptedException InterruptedException

wait() method causes the thread to sleep It can be used to add sequence among
until notify() and notifyAll() are called more than one thread

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Web Based Application in Java: Use of JavaScript for creating web


based applications in java, Introduction to javascript frameworks-
React, Vue, Angular

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Web Client (browser)

Internet

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Web Server

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Web Surfing (Logical View)

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Establishing Communication

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Inetwork Basis
● TCP/IP protocol
– Transmission Control Protocol and Internet Protocol
– Specifies how two computer exchange data
● HTML
– Content-based or structural markup language, where the codes describe
what the contents of the document are.
– Codes are used to indicate the various parts of the document, such as
headings, paragraphs, lists, etc
● IP address
– Every computer has a unique IP address
– 32 bits in three 8 bit number groups
– 131.96.142.17

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

URL Examples

●Full URL
– http://www.uum.edu.my/welcome.htm
– http://www.stm1.uum.edu.my/index.html
– http://www.maxis.net.my/
– http://www.lhdn.gov.my/
●Not all characters can be used in URL

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Web Application Development

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Static VS Dynamic
● HTML documents are usually static
● The contents can only be changed manually
● There are needs for dynamic documents
– Search results
– Database access
– Context sensitive reply
● Static
– page appears exactly as it was encoded, nothing changes
● Dynamic
– page is compiled, or able to be changed

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Dynamic Web pages

●Applications executed by the server at run-


time to process client input or generate
document in response to client request
●Generating dynamic Web pages requires
programming

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Scripts: Server-Side VS Client-Side


●Server-side
– the first type possible on the Web
– action occurs at the server
●Client-side
– generally easier to implement
– may be prepared and implemented offline
– action occurs on the client side (browser)

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Scripts: Server-Side VS Client-Side

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Client-Side Scripting
● Client side scripts are embedded inside HTML document.
They are interpreted by browser.
● When Web browser encounters a script, it calls a scripting
interpreter, which parses and deciphers the scripting code.
● Provide response to questions and queries without
interventions from the server
– Validate user data
– Calculate expressions
– Link to other applications

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JAVASCRIPT
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

LIBRARY Vs FRAMEWORK

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Scripting or Programming language


Allows to implement complex features on web
pages

Displaying timely content


updates
Interactive Maps

It is the third layer of the layer cake of standard web


technologies ..HTML, CSS, JS

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JAVA SCRIPT

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JAVA SCRIPT FEATURES

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

NEED/ ADVANTAGES OF JAVA SCRIPT

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Use to structure and give meaning to our


web content, for example defining
paragraphs, headings, and data tables, or
embedding images and videos in the
page.
To apply styling to our HTML
content, for example setting
background colors and fonts, and
laying out our content in multiple
columns.

To create dynamically
updating content, control
multimedia, animate images.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
<p>Player 1: Chris</p>

p{
font-family: 'helvetica neue', helvetica, sans-
serif;
letter-spacing: 1px;
text-transform: uppercase;
const para = document.querySelector('p');
text-align: center;
border: 2px solid rgba(0,0,200,0.6);
para.addEventListener('click', updateName);
background: rgba(0,0,200,0.3);
color: rgba(0,0,200,0.6);
function updateName() {
box-shadow: 1px 1px 2px
const name = prompt('Enter a new name');
rgba(0,0,200,0.4);
para.textContent = `Player 1: ${name}`;
border-radius: 10px;
}
padding: 3px 10px;
display: inline-block;
cursor: pointer;
}

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - Coding Ways/ Script


Placement
Script in Script in
<head>...</head> section. <body>...</body> section.

Script in an external file and


Script in
then include in
<head>and <body> section.
<head>...</head> section.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - Coding Ways/ Script


Placement
Script in Script in
<head>...</head> section. <body>...</body> section.

Script in an external file and


Script in
then include in
<head>and <body> section.
<head>...</head> section.

Note
In HTML, JavaScript code is inserted between
<script> and </script> tags.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - Example 1
Script in <html>
<head>...</head>
section.
<head>
<script>
document.write("Hello
World")
</script>
</head>
</html>

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - Example 1.1


Script in <html>
<head>...</head> <head>
section.
<script>
alert("Hello World")
</script>
</head>
</html>

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - Example 2
Script in <html>
<body>...</body>
section.
<body>
<script>
document.write("Hello
World")
</script>
</body>
</html>

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Example
4
<html>
Script in <head>
<head>and <script type = "text/javascript">
</body> <!--
section.
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Example 4 : Output

Script in
<head>and
</body> section.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Example
5
<html>
<head>
Script in <script type = "text/javascript" src = "filename.js" ></script>
an </head>
external
<body>
file and <h2>Demo External JavaScript</h2>
then
include in <button type="button" onclick="sayHello()">Try it</button>
</body>
<head>...< </html>
/head>
section.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Example 5 : Output

Script in
an
external
file and
then
include in
<head>...<
/head>
section.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - Vue
Open Source

Used to develop interactive web interfaces.

VueJS focusses on the view layer

It is easily integrated into big projects for front-end


development without any issues.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - Vue Example


<html>
<head>
<title>VueJs Introduction</title>
<script type = "text/javascript" src =
"js/vue.js"></script>
</head>
<body>
<div id = "intro" style = "text-align:center;">
<h1>{{ message }}</h1>
</div>
<script type = "text/javascript">
var vue_det = new Vue({
el: '#intro',
data: {
message: 'My first VueJS Task'
} Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Example Vue : Output

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - AngularJs

Powerful JavaScript Framework.

Used in Single Page Application (SPA) projects

Open Source

It extends HTML DOM with additional attributes and


makes it more responsive to user actions

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - AngularJs

It Uses Model View Controller Architecture


● Model - maintains the data
● View : Display of data/Appearance of data
● Controller : Interface between model and View

AngularJS framework can be divided into three major


parts

ng-app ng-model ng-bind

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - AngularJs

ng-app This directive defines and links an AngularJS application to HTML.

This directive binds the values of AngularJS application data


ng-model to HTML input controls.

This directive binds the AngularJS application data to


ng-bind HTML tags.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - AngularJS Example


<html>
<head>
<title>AngularJS First Application</title>
</head>

<body>
<h1>Sample Application</h1>

<div ng-app = "">


<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
</div>

<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>

</body>
</html>
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

JavaScript - ReactJS Example


https://slides.com/alexanderfarennikov/react-js-fundamentals/fullscreen#/4/7

import React fromp 'react';


import llogo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
Hello World !
</div>
);
}
export default App;

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

● Angular, developed by Google, was first


released in 2010, making it the oldest of the lot. It
is a TypeScript-based JavaScript framework.
● React, developed by Facebook, was initially
released in 2013. Facebook uses React
extensively in their products (Facebook,
Instagram, and WhatsApp).
● Vue, also known as Vue.js, is the youngest
member of the group. It was developed by ex-
Google employee Evan You in 2014.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering

You might also like