Java program 1
Java program 1
Swing components like JTextArea are not thread-safe. Therefore, all updates to the user interface
must beperformed ontheEvent DispatchThread(EDT). Whenbackgroundthreads attempt toupdate the
UI directly, the following problems can occur:
Raceconditions, wheremultiplethreadstrytoread/writetothesamecomponent
simultaneously.
Visualglitchesorapplicationcrashes,duetoinconsistentinternalUIstates.
Deadlocks,whenthreadsblock oneanother tryingtoaccesslockedGUIresources.
A. SwingUtilities.invokeLater()
Benefits:
- EnsuresallGUIupdatesoccursafelyontheEDT.
- PreventsdirectUImanipulationfromnon-EDT threads.
- AvoidsthreadinterferencewithSwingcomponents.
1
B. synchronizedBlocksforSharedData
Benefits:
- Preventsraceconditionswhensharedvariablesareaccessedconcurrently.
- Guaranteesthat onlyonethreadexecutesablockofcodeatatime.
- MaintainsconsistencyofsharedresourceslikeJTextArea.
2
C. volatileVariablesforThreadCommunication
Benefits:
- Ensureschangesmadebyonethreadareimmediatelyvisibletoothers.
- Preventslocalthreadcachingofstalevalues.
- Suitableforsimplecommunicationwithoutlockingoverhead.
D. CounterSynchronization(ifshared)
Prevents:
- Lostupdatesduetoconcurrentincrements.
- Inconsistentorincorrectcountervalues.
- Raceconditionsduringread-modify-writeoperations.
3
4
2.
class BankAccount {
private int balance = 0;
public synchronized void deposit(int amount, String threadName) {
balance += amount;
System.out.println(threadName + " deposited: " + amount + " | Balance: " + balance);
notifyAll();
}
public synchronized void withdraw(int amount, String threadName) {
while (balance < amount) {
System.out.println(threadName + " waiting to withdraw: " + amount + " | Balance: " +
balance);
try {
wait();
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted while waiting.");
return;
}
}
balance -= amount;
System.out.println(threadName + " withdrew: " + amount + " | Balance: " + balance);
}
}
class DepositThread extends Thread {
private BankAccount account;
private int amount;
public DepositThread(BankAccount account, int amount, String name) {
super(name);
this.account = account;
this.amount = amount;
}
public void run() {
for (int i = 0; i < 3; i++) {
account.deposit(amount, getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(getName() + " interrupted.");
}
}
}
}
super(group, name);
this.number = number;
@Override
long result = 1;
result *= i;
Math.sin(j);
System.out.println(getName() + " [Priority: " + getPriority() + "] - Factorial of " + number + " is
calculated.");
}
}
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.NORM_PRIORITY);
t4.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
t4.start();
Explanation
Thread.MAX_PRIORITY = 10
Thread.NORM_PRIORITY = 5
Thread.MIN_PRIORITY = 1
Thread scheduling is managed by the JVM and the OS, so higher-priority threads may get more CPU time,
but execution order is not guaranteed.
The JVM uses a priority-based, preemptive scheduling algorithm but delegates thread execution to the
host OS. On platforms like Windows, priorities are respected to a degree, but may not enforce strict
order. Therefore, thread priorities should be used for hints rather than control mechanisms.
OUTPUT
4.
class Matrix<T extends Number> {
private T[][] data;
import java.util.Arrays;
class SortValidator {
public static <T extends Comparable<T>> void sortAndValidate(T[] array) {
for (T item : array)
if (!item.getClass().equals(array[0].getClass()))
throw new IllegalArgumentException("Inconsistent types in array");
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
sortAndValidate(nums);
sortAndValidate(words);
sortAndValidate(students);
}
}
Explanation: Based on printArray, we ensure type consistency with runtime checks because
generics use type erasure.
6.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
checkBox.setSelected(true);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Explanation: Demonstrates interaction between components using listeners. Inspired by
SwingFirstExample and CheckBoxExample.
7.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawingApp extends JPanel {
private int x, y;
private boolean dragging = false;
public DrawingApp() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
x = e.getX(); y = e.getY(); dragging = false;
repaint();
}
public void mousePressed(MouseEvent e) {
dragging = true;
}
public void mouseReleased(MouseEvent e) {
dragging = false;
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
if (dragging) {
x = e.getX(); y = e.getY();
repaint();
}
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (dragging) {
g.setColor(Color.YELLOW);
g.fillRect(x - 10, y - 10, 20, 20);
} else {
g.setColor(Color.GREEN);
g.fillOval(x - 10, y - 10, 20, 20);
}
}
8.
import javax.swing.*;
new Thread(counterTask).start();
new Thread(timestampTask).start();
}
}
Explanation: Ensures thread safety via synchronization to avoid race conditions.
9.
import javax.swing.*;
import java.awt.event.*;
menuBar.add(fileMenu);
menuBar.add(editMenu);
frame.setJMenuBar(menuBar);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Explanation: Uses ActionListeners for menu items. Matches Swing’s MVC where JMenuBar
(View) notifies ActionListener (Controller) to handle logic.
QN:
Implement a generic class Buffer<T> that acts as a bounded buffer for a producer-consumer
scenario. The producer thread adds items of type T (e.g., String), and the consumer thread
removes them, using wait() and notifyAll() for synchronization. Test with a String buffer of size
5, and ensure thread safety. Explain how the document’s inter-thread communication and
generics examples influenced your design.
SOLUTION
Buffer<> implementation
Producer Threads& Consumer Threads
Output
Explanation;
The Buffer class uses an Array The “Buffer” class uses an “Array List<Integer>”to store items with a fixed
capacity. The producer thread adds one integer (`42`) to the buffer and prints confirmation. The consumer thread
retrieves the integer and also prints a message. ‘Wait () ` and `notify All () ` ensure that threads wait and notify each
other properly. The output confirms the production and consumption of a single integer item safely. List<Integer>
to store items with a fixed capacity. The producer thread adds one integer (42) to the buffer and
prints confirmation. The consumer thread retrieves the integer and also prints a message. Wait ()
and notify All () ensure that threads wait and notify each other properly. The output confirms the
production and consumption of a single integer item safely.
Consumed: 42 – The consumer thread takes the item from the buffer.