0% found this document useful (0 votes)
2 views

Java

The document provides an overview of multithreading in Java, highlighting its advantages such as non-blocking operations and efficient memory usage. It discusses synchronization, including types and methods for managing thread access to shared resources, and introduces applets, layout managers, and JDBC drivers. Key concepts include thread communication, mutual exclusion, and various layout managers for GUI design.

Uploaded by

iknowwhoiammr
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java

The document provides an overview of multithreading in Java, highlighting its advantages such as non-blocking operations and efficient memory usage. It discusses synchronization, including types and methods for managing thread access to shared resources, and introduces applets, layout managers, and JDBC drivers. Key concepts include thread communication, mutual exclusion, and various layout managers for GUI design.

Uploaded by

iknowwhoiammr
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Multithreading in Java

Multithreading in Java is a process of executing multiple threads


simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve
multitasking.

However, we use multithreading than multiprocessing because threads


use a shared memory area. They don't allocate separate memory area so
saves memory, and context-switching between the threads takes less
time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an


exception occurs in a single thread.

Synchronization in Java
Synchronization in Java is the capability to control the access of multiple
threads to any shared resource.

Java Synchronization is better option where we want to allow only one


thread to access the shared resource.

Why use Synchronization?


The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.
Types of Synchronization
There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-
thread communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another
while sharing data. It can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or
monitor. Every object has a lock associated with it. By convention, a
thread that needs consistent access to an object's fields has to acquire
the object's lock before accessing them, and then release the lock when
it's done with them.

1. class Table{
2. synchronized void printTable(int n){//synchronized method
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. }
9.
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
20. }
21.
22. }
23. class MyThread2 extends Thread{
24. Table t;
25. MyThread2(Table t){
26. this.t=t;
27. }
28. public void run(){
29. t.printTable(100);
30. }
31. }
32.
33. public class TestSynchronization2{
34. public static void main(String args[]){
35. Table obj = new Table();//only one object
36. MyThread1 t1=new MyThread1(obj);
37. MyThread2 t2=new MyThread2(obj);
38. t1.start();
39. t2.start();
40. }
41. }
Inter-thread Communication in Java
Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a


thread is paused running in its critical section and another thread is
allowed to enter (or lock) in the same critical section to be executed.It is
implemented by following methods of Object class:

o wait()
o notify()
o notifyAll()

1) wait() method
The wait() method causes current thread to release the lock and wait until
either another thread invokes the notify() method or the notifyAll()
method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called
from the synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is

public final void wait(long timeout)throws It waits for the spec


InterruptedException time.

2) notify() method
The notify() method wakes up a single thread that is waiting on this
object's monitor. If any threads are waiting on this object, one of them is
chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.

Syntax:

1. public final void notify()


3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

1. public final void notifyAll()

1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}

What is Applet?
An applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag
and hosted on a web server.
Applets are used to make the website more dynamic and entertaining.

Important points :

1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.

2. Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer. JDK provides a standard applet viewer tool called applet viewer.

3. In general, execution of an applet does not begin at main() method.

4. Output of an applet window is not performed by System.out.println(). Rather it is handled


with various AWT methods, such as drawString().

import java.applet.Applet;

import java.awt.Graphics;

public class SimpleApplet extends Applet {

// Initialization method

public void init() {

// Initialization code goes here

// Start method

public void start() {

// Code to start or resume the applet

}
// Paint method

public void paint(Graphics g) {

// Code to draw on the applet window

g.drawString("Hello, Applet!", 20, 20);

// Stop method

public void stop() {

// Code to suspend or stop the applet

// Destroy method

public void destroy() {

// Code to perform cleanup when the applet is about to be destroyed

<html>

<body>

<applet code="SimpleApplet.class" width="300" height="200">

</applet>

</body>

</html>

Types of Layout Manager in Java


In Java, graphical user interfaces (GUIs) play a vital role in creating
interactive applications. To design a visually appealing and organized
interface, the choice of layout manager becomes crucial. Layout
managers define how components are arranged within a container, such
as a JFrame or JPanel. Java provides several layout managers to suit
various design needs. In this section, we will delve into the details of the
different types of layout managers available in Java, along with code
examples and explanations.

1. FlowLayout
FlowLayout is a simple layout manager that arranges components in a
row, left to right, wrapping to the next line as needed. It is ideal for
scenarios where components need to maintain their natural sizes and
maintain a flow-like structure.

FlowLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class FlowLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("FlowLayout Example");
6. frame.setLayout(new FlowLayout());
7. frame.add(new JButton("Button 1"));
8. frame.add(new JButton("Button 2"));
9. frame.add(new JButton("Button 3"));
10. frame.pack();
11. frame.setVisible(true);
12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
13. }
14. }

Output:

2. BorderLayout
BorderLayout divides the container into five regions: NORTH, SOUTH,
EAST, WEST, and CENTER. Components can be added to these regions,
and they will occupy the available space accordingly. This layout manager
is suitable for creating interfaces with distinct sections, such as a title bar,
content area, and status bar.

BorderLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class BorderLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("BorderLayout Example");
6. frame.setLayout(new BorderLayout());
7. frame.add(new JButton("North"), BorderLayout.NORTH);
8. frame.add(new JButton("South"), BorderLayout.SOUTH);
9. frame.add(new JButton("East"), BorderLayout.EAST);
10. frame.add(new JButton("West"), BorderLayout.WEST);
11. frame.add(new JButton("Center"), BorderLayout.CENTER)
;
12. frame.pack();
13. frame.setVisible(true);
14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
15. }
16. }

Output:

3. GridLayout
GridLayout arranges components in a grid with a specified number of rows
and columns. Each cell in the grid can hold a component. This layout
manager is ideal for creating a uniform grid of components, such as a
calculator or a game board.

GridLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class GridLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("GridLayout Example");
6. frame.setLayout(new GridLayout(3, 3));
7. for (int i = 1; i <= 9; i++) {
8. frame.add(new JButton("Button " + i));
9. }
10. frame.pack();
11. frame.setVisible(true);
12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
13. }
14. }

Output:

4. CardLayout
CardLayout allows components to be stacked on top of each other, like a
deck of cards. Only one component is visible at a time, and you can switch
between components using methods like next() and previous(). This
layout is useful for creating wizards or multi-step processes.
CardLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.ActionEvent;
4. import java.awt.event.ActionListener;
5. public class CardLayoutExample {
6. public static void main(String[] args) {
7. JFrame frame = new JFrame("CardLayout Example");
8. CardLayout cardLayout = new CardLayout();
9. JPanel cardPanel = new JPanel(cardLayout);
10. JButton button1 = new JButton("Card 1");
11. JButton button2 = new JButton("Card 2");
12. JButton button3 = new JButton("Card 3");
13. cardPanel.add(button1, "Card 1");
14. cardPanel.add(button2, "Card 2");
15. cardPanel.add(button3, "Card 3");
16. frame.add(cardPanel);
17. frame.pack();
18. frame.setVisible(true);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
20. button1.addActionListener(e -> cardLayout.show(cardPa
nel, "Card 2"));
21. button2.addActionListener(e -> cardLayout.show(cardPa
nel, "Card 3"));
22. button3.addActionListener(e -> cardLayout.show(cardPa
nel, "Card 1"));
23. }
24. }

Output:
5. GroupLayout
GroupLayout is a versatile and complex layout manager that provides
precise control over the positioning and sizing of components. It arranges
components in a hierarchical manner using groups. GroupLayout is
commonly used in GUI builders like the one in NetBeans IDE.

GroupLayoutExample.java

1. import javax.swing.*;
2. public class GroupLayoutExample {
3. public static void main(String[] args) {
4. JFrame frame = new JFrame("GroupLayout Example");
5. JPanel panel = new JPanel();
6. GroupLayout layout = new GroupLayout(panel);
7. panel.setLayout(layout);
8. JButton button1 = new JButton("Button 1");
9. JButton button2 = new JButton("Button 2");
10. layout.setHorizontalGroup(layout.createSequentialGroup(
)
11. .addComponent(button1)
12. .addComponent(button2));
13. layout.setVerticalGroup(layout.createParallelGroup()
14. .addComponent(button1)
15. .addComponent(button2));
16. frame.add(panel);
17. frame.pack();
18. frame.setVisible(true);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
20. }
21. }

Output:
6. GridBagLayout
GridBagLayout is a powerful layout manager that allows you to create
complex layouts by specifying constraints for each component. It arranges
components in a grid, but unlike GridLayout, it allows components to span
multiple rows and columns and have varying sizes.

GridBagLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class GridBagLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("GridBagLayout Example");
6. JPanel panel = new JPanel(new GridBagLayout());
7. GridBagConstraints constraints = new GridBagConstraints();
8. constraints.fill = GridBagConstraints.HORIZONTAL;
9. JButton button1 = new JButton("Button 1");
10. JButton button2 = new JButton("Button 2");
11. constraints.gridx = 0;
12. constraints.gridy = 0;
13. panel.add(button1, constraints);
14. constraints.gridx = 1;
15. panel.add(button2, constraints);
16. frame.add(panel);
17. frame.pack();
18. frame.setVisible(true);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
20. }
21. }

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC br
converts JDBC method calls into the ODBC function calls. This is now discouraged because of t

In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of your
database instead of the JDBC-ODBC Bridge.

Advantages:

o easy to use.
o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the


ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDB
native calls of the database API. It is not written entirely in java.

Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that
converts JDBC calls directly or indirectly into the vendor-specific database
protocol. It is fully written in java.
Advantage:

o No client side library is required because of application server that can


perform many tasks like auditing, load balancing, logging etc.

Disadvantages:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it
requires database-specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.
Advantage:

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage:

o Drivers depend on the Database.

MVC Architecture in Java


The Model-View-Controller (MVC) is a well-known design pattern in the
web development field. It is way to organize our code. It specifies that a
program or application shall consist of data model, presentation
information and control information. The MVC pattern needs all these
components to be separated as different objects.

In this section, we will discuss the MVC Architecture in Java, alongwith its
advantages and disadvantages and examples to understand the
implementation of MVC in Java.

What is MVC architecture in Java?


The model designs based on the MVC architecture follow MVC design
pattern. The application logic is separated from the user interface while
designing the software using model designs.

The MVC pattern architecture consists of three layers:

o Model: It represents the business layer of application. It is an object


to carry the data that can also contain the logic to update controller
if data is changed.
o View: It represents the presentation layer of application. It is used
to visualize the data that the model contains.
o Controller: It works on both the model and view. It is used to
manage the flow of application, i.e. data flow in the model object
and to update the view whenever data is changed.

In Java Programming, the Model contains the simple Java classes, the View
used to display the data and the Controller contains the servlets. Due to
this separation the user requests are processed as follows:

1. A client (browser) sends a request to the controller on the server


side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.

Advantages of MVC Architecture


The advantages of MVC architecture are as follows:
o MVC has the feature of scalability that in turn helps the growth of
application.
o The components are easy to maintain because there is less
dependency.
o A model can be reused by multiple views that provides reusability of
code.
o The developers can work with the three layers (Model, View, and
Controller) simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not
require to deal with massive code.
o The extending and testing of application is easier.

Implementation of MVC using Java


To implement MVC pattern in Java, we are required to create the following
three classes.

o Employee Class, will act as model layer


o EmployeeView Class, will act as a view layer
o EmployeeContoller Class, will act a controller layer

You might also like