0% found this document useful (0 votes)
4 views19 pages

Unit 5

The document discusses the differences between multiprocessing and multithreading, explaining their definitions, resource sharing, overhead, and use cases. It also outlines the life cycle of a thread in Java, detailing the various states a thread can be in, such as New, Runnable, Running, Blocked, Waiting, Timed Waiting, and Terminated. Additionally, it compares ReactJS, VueJS, and AngularJS in terms of their features, advantages, and disadvantages, while also explaining Java thread methods like isAlive() and join(), and ways to implement threads in Java.

Uploaded by

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

Unit 5

The document discusses the differences between multiprocessing and multithreading, explaining their definitions, resource sharing, overhead, and use cases. It also outlines the life cycle of a thread in Java, detailing the various states a thread can be in, such as New, Runnable, Running, Blocked, Waiting, Timed Waiting, and Terminated. Additionally, it compares ReactJS, VueJS, and AngularJS in terms of their features, advantages, and disadvantages, while also explaining Java thread methods like isAlive() and join(), and ways to implement threads in Java.

Uploaded by

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

1.

Difference between Multiprocessing and Multithreading

Feature Multithreading Multiprocessing Multitasking


Multiple threads Multiple processes
within a single run simultaneously Running multiple tasks or programs at the
Definition
process run on multiple CPUs or same time on a computer.
concurrently. cores.
Processes
Units of Threads (lightweight
(independent Tasks (could be processes or threads)
execution processes)
programs)
Threads share the
Processes have
Resource same memory and Depends on whether tasks are
separate memory
sharing resources of the processes or threads.
spaces and resources.
process.
Less overhead, Higher overhead due
Overhead faster context to separate memory Varies depending on implementation.
switching. for each process.
Improving Running multiple
Handling multiple user programs or system
Used for performance within applications or heavy
tasks.
a single application. parallel jobs.
Running a browser
Web browser
and a word processor Using several apps like browser,
Example running multiple
at the same time music player simultaneously.
tabs (threads).
(processes).

Explain life cycle of Thread model in Java.

🔹 1. New
 When you create a thread using new Thread(), it is in the
new state.
 The thread is not yet started.
 Example:
Thread t = new Thread(); // New state

🔹 2. Runnable
 After calling start(), the thread enters the runnable
state.
 The thread is ready to run but waiting for CPU time.
 It may be running or just waiting to be picked by the
CPU.
 Managed by Thread Scheduler.

🔹 3. Running
 The thread is actively executing its run() method.
 Only one thread runs at a time per CPU core.

🔹 4. Blocked
 A thread enters blocked state if it tries to enter a
synchronized block but another thread is already using
the lock.
 It waits until the lock is free.
 After getting the lock, it moves back to runnable state.

🔹 5. Waiting
 A thread goes into waiting state when it waits for
another thread’s signal (no time limit).
 Happens when methods like wait() or join() are called.
 It moves back to runnable when notified or the joined
thread finishes.

🔹 6. Timed Waiting
 A thread waits for a specific time using methods like:
o sleep(ms)
o wait(ms)
o join(ms)
 After the time ends, or if it's notified, it goes back to
runnable.

🔹 7. Terminated (Dead)
 A thread enters this state when:
o Its task is finished, or
o An error/exception occurs.
 It cannot run again after reaching this state

Feature React JS Vue JS Angular JS

JavaScript JavaScript JavaScript


Type
Library Framework Framework

Evan You
Developed By Facebook (Community- Google
driven)

Easy to
Moderate (JSX Steep (full-
Learning Moderate
syntax can be featured
Curve (simple
tricky) framework)
templates)

Component-
Component-based,
based, view MVC (Model-View-
Architecture focused on UI
layer + Controller)
only
ecosystem

One-way data Two-way data Two-way data


Data Binding
binding binding binding
Feature React JS Vue JS Angular JS

Very small
Size Small (~30KB) Large (~500KB)
(~20KB)

Very flexible,
Flexible and
needs extra libs Complete solution
Flexibility easy to
for out of the box
integrate
routing/state

High
High performance performance Slightly slower
Performance
with virtual DOM with virtual due to real DOM
DOM

Large, but less


Very large and
Community Growing rapidly growing than
active
React

Google
Use Case Facebook,insta Alibaba,xiaomi
workspace,upwork

3.Short Note on AngularJS

🔹 Key Concepts in AngularJS


1. Two-Way Data Binding
o If you change something in the web page, the data in
the code updates automatically, and vice versa.
o No need to manually update the UI and data
separately.
2. MVC Architecture
o Model = data
o View = user interface
o Controller = logic that connects model and view
o This separation helps organize the code neatly.
3. Directives
o Special tags or attributes in HTML (like ng-model,
ng-repeat, ng-if) that tell AngularJS what to do.
o Example:
<input ng-model="name">
<p>Hello {{name}}</p>
4. Templates
o AngularJS uses HTML templates to display data
dynamically using {{ }} syntax.
5. Dependency Injection
o AngularJS can automatically give your app the tools
(called services) it needs to work, like $http for
making web requests.

✅ Advantages of AngularJS

1. 🌐 Two-Way Data Binding


o Makes it easier to sync data between UI and logic
code.

2. 🧩 Reusable Components
o You can create small parts (components) and use them
again, saving time.

3. 📐 MVC Structure
o Keeps your app organized and easy to manage.

4. ⚙️ Built-in Services
o Has ready-to-use tools for tasks like form
validation and sending HTTP requests.

5. 🧪 Easy to Test
o AngularJS was designed with testing in mind, so
writing test cases is simple.

6. 🔄 Single Page Application (SPA) Support


o Lets users navigate without refreshing the entire
page.
❌ Disadvantages of AngularJS

1. 🧠 Difficult to Learn at First


o Concepts like $scope, directives, and two-way
binding can be confusing for beginners.

2. 🐢 Slower for Large Apps


o When there is too much data or logic, the app may
become slow.

3. ❌ Not SEO Friendly


o Search engines may not see content properly because
it is loaded using JavaScript.

4. 🧱 Complex Debugging
o Debugging nested components and scopes can be
tricky.

5. 🕒 Old Technology
o AngularJS (version 1.x) is now outdated and replaced
by newer versions (Angular 2+), which are faster and
more efficient.

Q5) Explain Methods in Java Thread [9 Marks]

🔹 i) getPriority()
 This method is used to get the priority of a thread.
 Thread priority is a number between 1 (lowest) and 10
(highest).
 The default priority is 5.
 This method helps to check what priority a thread has.

🔹 ii) setPriority()
 This method is used to set the priority of a thread.
 You can give a thread a priority between:
o 1 → MIN_PRIORITY
o 5 → NORM_PRIORITY (default)
o 10 → MAX_PRIORITY
 Higher priority threads get more chances to run, but not
guaranteed. It depends on the OS.

🔹 iii) notifyAll()
 This method is used to wake up all threads that are
waiting on the same object.
 It is used inside a synchronized block or method.
 All waiting threads will become runnable, but only one
will run at a time.
 Useful when many threads are paused and you want to
resume them together.
Q6 ) Features of ReactJS, AngularJS, and VueJS

🔹 ReactJS
ReactJS is a JavaScript library developed by Facebook for
building user interfaces, especially single-page applications.

⭐ Key Features:
1. Component-Based
o UI is divided into reusable components.
2. Virtual DOM
o Uses a virtual copy of the real DOM, which makes
updates faster and more efficient.
3. One-Way Data Binding
o Data flows in one direction: from parent to child
component.
4. JSX (JavaScript + HTML)
o Allows writing HTML-like code inside JavaScript,
making code easier to read.
5. Fast Rendering
o Due to virtual DOM, React apps perform better.
6. Strong Community Support
o Maintained by Facebook and widely used in the
industry.

🔹 VueJS
VueJS is a progressive JavaScript framework used for building
UIs and SPAs, created by Evan You.

⭐ Key Features:
1. Reactive Data Binding
o Like Angular, Vue binds data between model and view.
2. Component-Based
o Applications are built using independent and
reusable components.
3. Lightweight and Fast
o Vue is small in size and loads quickly.
4. Simple and Easy to Learn
o Easier for beginners to understand compared to
Angular.
5. Directives
o Custom directives like v-model, v-if, and v-for to
bind data and logic.
6. Flexibility
o Vue can be used for simple tasks or scaled for large
applications.
7.Differentiate between process and thread.

Point Process Thread

A thread is a smaller
A process is an
part of a process (also
Definition independent program in
called a lightweight
execution.
process).
Point Process Thread

Each process has its Threads share the same


Memory Usage
own memory space. memory of the process.

Processes use inter- Threads communicate


Communication process communication directly through shared
(IPC) which is slower. memory (faster).

Processes are Threads are dependent on


Execution independent of each the process they belong
other. to.

More overhead due to Less overhead; switching


Overhead context switching between threads is
between processes. faster.

If one process crashes, If one thread crashes,


Crash Impact it usually does not it can affect the whole
affect others. process.

Takes more time to Takes less time to


Creation Time
create. create.

Multiple tabs in Chrome


Running two apps like
Example run as threads inside
Chrome and Word.
one process.

6.Detailed Explanation of isAlive() and join() Methods in Java


Multithreading

🔹 1. isAlive() Method
 The isAlive() method is used to check the current state
of a thread.
 It tells you whether the thread has started and is still
running or if it has completed its execution.
 When a thread is created but not yet started, isAlive()
returns false.
 When the thread has started and is still running or ready
to run, isAlive() returns true.
 Once the thread has finished running (terminated),
isAlive() returns false again.
 This method is helpful in thread monitoring and
management to understand if a thread is active or
finished.
 ➤ Syntax:
 boolean isAlive(
class MyThread extends Thread {
public void run() {
System.out.println("Thread started.");
try {
Thread.sleep(2000); // Simulate work by pausing for 2 seconds
} catch (InterruptedException e) {}
System.out.println("Thread finished.");
}
}

public class Main {


public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start(); // Starts the new thread and calls run()

System.out.println("Is thread alive? " + t.isAlive());


// Prints true because the thread is still running (sleeping for 2
seconds)

t.join(); // Main thread waits here until thread t finishes


execution

System.out.println("Is thread alive after join? " + t.isAlive());


// Prints false because thread t has finished execution after
join()
}
}
Step-by-step:
We create a new thread t by extending the Thread class and overriding
run().

Inside run(), the thread prints "Thread started," then pauses for 2 seconds
to simulate work.

After calling t.start(), the thread begins executing run() concurrently.

Immediately after, the main thread checks t.isAlive(), which returns true
since t is sleeping.

The main thread then calls t.join(), which pauses the main thread until
thread t finishes.

After t finishes, main resumes and checks t.isAlive() again, now returning
false because t completed.

🔹 2. join() Method
 The join() method is used to make one thread wait for
another thread to finish before continuing.
 When a thread calls join() on another thread, it pauses
its own execution until the other thread completes its
task and dies.
 This is useful when you want to ensure that one thread
finishes its work before the program proceeds to the next
step.
 join() has two forms:
o join() with no parameters: waits indefinitely until
the target thread finishes.
o join(long millis): waits for a specified time in
milliseconds. If the thread does not finish in that
time, it continues anyway.
 By using join(), you can achieve synchronization between
threads, making the program flow predictable and avoiding
problems like accessing incomplete data.

 ➤ Syntax:
 void join() // waits until the thread dies
 void join(long millis) // waits for the specified time

EXAMPLE
class MyThread extends Thread {
public void run() {
System.out.println("Thread running...");
try {
Thread.sleep(3000); // Simulate a long task (3 seconds)
} catch (InterruptedException e) {}
System.out.println("Thread completed.");
}
}

public class Main {


public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start(); // Start the thread which runs concurrently

System.out.println("Waiting for thread to finish...");


t.join(); // Main thread waits here until thread t completes

System.out.println("Main thread resumes after join.");


}
}
Step-by-step:
Thread t is created and started; it prints "Thread running..." and then
sleeps for 3 seconds.

Meanwhile, the main thread prints "Waiting for thread to finish..." and
immediately calls t.join().

The main thread pauses execution at join() until thread t finishes its
sleep and prints "Thread completed."

Only after t finishes, the main thread resumes and prints "Main thread
resumes after join."

8.Different Ways to Implement Threads in Java


1️⃣ Extending the Thread Class
 You create a new class that extends the Thread class.
 Override the run() method with the code you want the thread to
execute.
 Create an object of this class and call start() to begin the thread.
Example:
java
CopyEdit
class MyThread extends Thread {
public void run() {
System.out.println("Thread running using Thread class");
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Start the thread
}
}

2️⃣ Implementing the Runnable Interface


 Create a class that implements the Runnable interface.
 Implement the run() method with the thread’s task.
 Pass the object of this class to a Thread constructor.
 Call start() on the Thread object to begin.
Example:
java
CopyEdit
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running using Runnable interface");
}
}

public class Main {


public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t1 = new Thread(r);
t1.start(); // Start the thread
}
}

3️⃣ Using Lambda Expression (Java 8 and above)


 Since Runnable is a functional interface, you can use a lambda
expression to implement it in a shorter way.
Example:
java
CopyEdit
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
System.out.println("Thread running using Lambda expression");
});
t1.start();
}
}

10.Vue.js
Advantages:
 Easy to Learn: Simple syntax and clear documentation make
it beginner-friendly.
 Lightweight: Small file size means faster loading and
better performance.
 Reactive Data Binding: Automatically updates the UI when
data changes.
 Component-Based: Reusable components make development
modular and organized.
 Flexible: Can be used for simple projects or large-scale
apps.
 Good Integration: Easily integrates with other libraries
or existing projects.
Limitations:
 Smaller Community: Compared to React, fewer resources and
third-party libraries.
 Language Barrier: Some documentation and community
support is more focused on Chinese users.
 Not Backed by Large Corporation: Less corporate support
than React (Facebook) or Angular (Google).
 Less Job Market: Fewer job openings compared to React or
Angular.

11.React.js

Advantages:
 Large Community: Extensive ecosystem and lots of
tutorials, libraries, and tools.
 Virtual DOM: Improves performance by minimizing direct
DOM manipulation.
 Reusable Components: Enables modular UI development.
 Strong Corporate Backing: Maintained by Facebook,
ensuring long-term support and stability.
 Rich Ecosystem: Works well with many tools and third-
party libraries.
 SEO Friendly: Can be optimized for search engines better
than many other JavaScript frameworks.
Limitations:
 Steep Learning Curve: JSX and complex state management
can be difficult for beginners.
 Only UI Library: React handles UI only, so you need
additional libraries for routing, state management, etc.
 Frequent Updates: Rapid changes sometimes make
maintaining large projects challenging.
 Boilerplate Code: Setting up complex projects may require
writing extra code and configuration.
12.Features of JavaScript
1. Lightweight and Interpreted – Runs directly in the
browser without compilation.
2. Client-side Scripting – Primarily used to create
interactive web pages.
3. Dynamic Typing – Variable types are determined at
runtime.
4. Object-Oriented – Supports objects and prototypes.
5. Event-Driven – Responds to user actions like clicks,
input, etc.
6. Cross-Platform – Works on all modern browsers and
operating systems.
7. Functional Programming Support – Supports functions as
first-class citizens.
8. Asynchronous Programming – Supports callbacks, promises,
and async/await.
9. Easy to Learn – Simple syntax with widespread community
support.
10. Embedded in HTML – Can be directly embedded in web
pages.

Welcome Message in JavaScript


<!DOCTYPE html>
<html>
<head>
<title>Welcome Message</title>
</head>
<body>

<h2>Welcome Message using JavaScript</h2>

<script>
// Display welcome message in an alert box
alert("Welcome to JavaScript!");

// Display welcome message in the browser console


console.log("Welcome to JavaScript!");

// Display welcome message on the web page


document.write("Welcome to JavaScript!");
</script>

</body>
</html>
JS LOGIN PAGE
<!DOCTYPE html>
<html>
<body>

<h2>Simple Login</h2>
Username: <input type="text" id="user"><br><br>
Password: <input type="password" id="pass"><br><br>

<button onclick="login()">Login</button>

<p id="msg"></p>

<script>
function login() {
var username = document.getElementById("user").value;
var password = document.getElementById("pass").value;

if(username == "admin" && password == "1234") {


document.getElementById("msg").innerText = "Login
Successful!";
} else {
document.getElementById("msg").innerText = "Invalid
username or password.";
}
}
</script>

</body>
</html>

What is Thread Synchronization?


When multiple threads run concurrently, they might try to
access and modify the same shared resource (like a variable,
object, or file). If these accesses are not controlled
properly, it can cause unexpected problems such as:
 Data inconsistency — Threads may overwrite each other’s
changes.
 Race conditions — The final outcome depends on the timing
of threads, leading to unpredictable behavior.
Thread synchronization is the technique used to ensure that
only one thread accesses the shared resource at a time,
preventing these problems and making the program thread-safe.

How to Achieve Thread Synchronization in Java


Java provides built-in support for synchronization using the
synchronized keyword. It can be applied in two ways:
1. Synchronized Methods
 When a method is declared with synchronized, only one
thread can execute this method on the same object
instance at any given time.
 Other threads trying to call this method on the same
object have to wait until the first thread finishes.
Example:
java
CopyEdit
public class Counter {
private int count = 0;

public synchronized void increment() {


count++; // critical section
}

public int getCount() {


return count;
}
}
Here, the increment() method is synchronized. If multiple
threads call increment() on the same Counter object, only one
thread can execute it at a time, avoiding race conditions.
2. Synchronized Blocks
 Sometimes, only a small part of a method needs
synchronization. In such cases, you can use a
synchronized block.
 It synchronizes only the code inside the block, reducing
overhead and improving performance.
 The block uses an object lock, usually this (the current
object) or another specific object.
Example:
java
CopyEdit
public class Counter {
private int count = 0;

public void increment() {


synchronized(this) { // synchronized block
count++;
}
}

public int getCount() {


return count;
}
}
Here, only the increment operation is synchronized, and other
code outside this block can run concurrently.

What Happens During Synchronization?


 When a thread enters a synchronized method/block, it
acquires a lock on the object used for synchronization.
 Other threads trying to enter any synchronized
method/block on the same object must wait until the lock
is released.
 Once the thread completes the synchronized code, it
releases the lock, allowing other threads to enter.

Important Points:
 Synchronization works at the object level, not the class
level. If two threads work on different objects of the
same class, they can execute synchronized methods
independently.
 For static synchronized methods, the lock is on the class
object itself.
 Overusing synchronization can cause performance issues
and may lead to deadlocks if not managed carefully.

You might also like