Java Assignment
Name: Sriram Bingi
Roll No: 24261A0578
1. Why Thread Synchronization is needed? Explain with an example.
Thread synchronization in Java is used to control the access of multiple threads to shared resources.
When two or more threads try to modify the same data at the same time, it creates a race condition,
which leads to incorrect or inconsistent results. To avoid this situation, Java provides synchronized
methods/blocks which ensure that only one thread executes the critical section at a time.
Example Without Synchronization:
class Counter {
int count = 0;
void increment() { count++; }
}
Correct Version Using Synchronization:
class Counter {
int count = 0;
synchronized void increment() { count++; }
}
2. Compare different layout managers and explain how they organize UI components.
FlowLayout: Arranges components left to right.
BorderLayout: Divides the window into North, South, East, West, Center.
GridLayout: Divides into equal rows and columns.
GridBagLayout: Flexible grid layout.
CardLayout: Displays one component at a time.
3. AWT Containers Differences with Examples.
Frame: Independent window with title bar.
Panel: Sub-container to group components.
Dialog: Popup window dependent on Frame.
Applet: Runs inside browser or viewer.
4. Java Program: Traffic Signal Controller using Swing.
import [Link].*;
import [Link].*;
import [Link].*;
public class TrafficSignal extends JFrame implements ActionListener {
JButton redBtn, yellowBtn, greenBtn;
JLabel lightLabel;
...
}
5. JTable Example Program.
import [Link].*;
public class TableExample {
public static void main(String[] args) {
JFrame f = new JFrame("JTable Example");
...
}
}