unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

UNIT 3 TWO MARKS

1. What is the purpose of implementing Interface in Java?

o An interface is a reference type in Java.


o It contains only abstract methods (before Java 8) and constants.
o It defines a contract that implementing classes must follow.
o Interfaces support multiple inheritance by allowing a class to implement multiple
interfaces.
2. How do you implement an interface in Java?
o A class uses the implements keyword to implement an interface.
o The class must provide concrete implementations for all abstract methods.
o Multiple interfaces can be implemented by a single class.
o The class must follow the method signatures as defined in the interface.
3. Differentiate class and interface

o A class can contain concrete methods, while an interface contains abstract


methods (before Java 8).
o A class supports inheritance, while an interface supports implementation.
o Multiple inheritance is not allowed for classes but is possible with interfaces.
o Classes use constructors, but interfaces do not.

4. What is extending an interface in Java?


o An interface can extend another interface using the extends keyword.
o It allows one interface to inherit methods from another.
o The extended interface can have its own additional methods.
o The class implementing the extended interface must implement all methods from
both interfaces.
5. What is object cloning in Java?
o Object cloning creates a copy of an object.
o It is achieved using the clone() method from the Cloneable interface.
o Cloning can be shallow or deep.
o The clone() method throws a CloneNotSupportedException if the class
doesn't implement Cloneable.
6. What are inner classes in Java?
o An inner class is a class defined within another class.
o It has access to the members of the outer class, including private members.
o Inner classes can be static or non-static.
o They are used to logically group classes that are only used in one place.
7. What is the this keyword in Java?
o this is a reference to the current object.
o It is used to differentiate between instance variables and parameters with the same
name.
o It can be used to call another constructor in the same class.
o this is commonly used in setter methods.
8. What is the super keyword in Java?
o super refers to the immediate parent class object.
o It is used to access parent class members, including constructors.
o super() can be used to call the parent class constructor.
o It is also used to invoke methods or access fields from the parent class.
9. What is the difference between multithreading and multitasking?

10. What is inter thread communication in Java?


o Inter-thread communication in Java is a mechanism that allows threads to
communicate with each other using synchronization.
o It enables threads to cooperate while accessing shared resources, avoiding
conflicts and improving efficiency.
o The communication is achieved through methods like wait(), notify(), and
notifyAll() from the Object class.
o These methods allow a thread to pause its execution until a specific condition is
met, and then resume when another thread signals that the condition has changed,
ensuring smooth coordination between threads.

11. What are the states in thread life cycles in Java?

 New: The thread is created but not started.


 Runnable: The thread is ready to run but waiting for CPU time.
 Blocked/Waiting: The thread is waiting for resources or another thread.
 Terminated: The thread has completed execution.

I. Thread Creation .thread class Runnable Class with


example
Thread Creation in Java

Java provides two main ways to create threads:

1. Extending the Thread class


2. Implementing the Runnable interface

1. Using the Thread Class


 To create a thread by extending the Thread class, you need to create a subclass of Thread
and override its run() method, which contains the code that will execute in the thread.

PROGRAM:

class MyThread extends Thread {

public void run() {

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

System.out.println("Thread: " + i);

try {

Thread.sleep(500); // Sleep for 500 milliseconds

} catch (InterruptedException e) {

System.out.println(e);

public static void main(String[] args) {

MyThread t1 = new MyThread();

t1.start(); // Start the thread

OUTPUT:

Thread: 1

Thread: 2

Thread: 3

Thread: 4
Thread: 5

The output consists of the lines "Thread: 1", "Thread: 2", etc., printed in sequence. The output
order may vary depending on thread scheduling by the JVM.

Class Declaration:

 class MyThread extends Thread: This declares a class MyThread that extends the
Thread class. By extending Thread, MyThread can override the run() method to
define the code that will execute in the thread.

Overriding the run() Method:

 public void run():


This method contains the code that runs in the new thread. In
this example, a loop runs five times, printing the current value of i.

Thread Sleep:

 Thread.sleep(500):
This pauses the execution of the current thread for 500
milliseconds. It simulates a time-consuming task and allows other threads to
run.

Error Handling:

 The InterruptedException is caught in case the thread is interrupted while


sleeping.

Main Method:

 public static void main(String[] args): The entry point of the program.
 MyThread t1 = new MyThread(): A new thread instance is created.
 t1.start(): This method starts the thread, which in turn calls the run() method.

2. Using the Runnable Interface


 The Runnable interface is another way to create a thread. You implement the Runnable
interface and define the run() method. Then, you create a Thread object with an instance of
your class.

PROGRAM:

class MyRunnable implements Runnable {


public void run() {

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

System.out.println("Runnable: " + i);

try {

Thread.sleep(500); // Sleep for 500 milliseconds

} catch (InterruptedException e) {

System.out.println(e);

public static void main(String[] args) {

MyRunnable myRunnable = new MyRunnable();

Thread t2 = new Thread(myRunnable);

t2.start(); // Start the thread

Class Declaration:

 class MyRunnable implements Runnable: This declares a class MyRunnable that


implements the Runnable interface. By doing this, MyRunnable must implement
the run() method.

Implementing the run() Method:

 public void run():


Similar to the previous example, this method contains the
code to execute in the thread. The loop prints the current value of i, with a
sleep period to simulate a task.

Main Method:
 public static void main(String[] args): The main method where execution starts.
 MyRunnable myRunnable = new MyRunnable(): An instance of MyRunnable is created.
 Thread t2 = new Thread(myRunnable): A new Thread object is created, passing the
myRunnable instance to its constructor.
 t2.start(): This starts the new thread, which calls the run() method of MyRunnable.

OUTPUT:

Runnable: 1

Runnable: 2

Runnable: 3

Runnable: 4

Runnable: 5

The output consists of "Runnable: 1", "Runnable: 2", etc., printed in sequence, similar to the
first example. Again, the output order may vary.

II. Inter thread communication with program


 Inter-thread Communication: Mechanism allowing threads to communicate and synchronize
their actions.
 Wait-Notify Mechanism: Threads can wait for a condition to be satisfied, and notify other
threads when that condition changes.

Key Methods:

1. wait():
o Causes the current thread to wait until another thread invokes notify() or
notifyAll() on the same object.
o Must be called from a synchronized context.
2. notify():
o Wakes up a single thread that is waiting on the object's monitor.
o If multiple threads are waiting, one of them is chosen at the discretion of the thread
scheduler.

Example: Producer-Consumer Problem

Overview:

 Producer: Generates data and puts it into a shared buffer.


 Consumer: Retrieves data from the buffer.
 The buffer has a limited capacity, so the producer must wait if the buffer is full, and the
consumer must wait if the buffer is empty.

import java.util.LinkedList;

import java.util.Queue;

class SharedBuffer {

private final Queue<Integer> buffer = new LinkedList<>();

private final int capacity;

public SharedBuffer(int capacity) {

this.capacity = capacity;

public void produce(int value) throws InterruptedException {

synchronized (this) {

while (buffer.size() == capacity) {

wait(); // Wait if the buffer is full

buffer.add(value);

System.out.println("Produced: " + value);

notify(); // Notify a waiting consumer

public int consume() throws InterruptedException {

synchronized (this) {

while (buffer.isEmpty()) {

wait(); // Wait if the buffer is empty


}

int value = buffer.poll();

System.out.println("Consumed: " + value);

notify(); // Notify a waiting producer

return value;

class Producer extends Thread {

private final SharedBuffer buffer;

public Producer(SharedBuffer buffer) {

this.buffer = buffer;

public void run() {

for (int i = 0; i < 10; i++) {

try {

buffer.produce(i);

Thread.sleep(500); // Simulate time taken to produce

} catch (InterruptedException e) {

System.out.println(e);

}
class Consumer extends Thread {

private final SharedBuffer buffer;

public Consumer(SharedBuffer buffer) {

this.buffer = buffer;

public void run() {

for (int i = 0; i < 10; i++) {

try {

buffer.consume();

Thread.sleep(1000); // Simulate time taken to consume

} catch (InterruptedException e) {

System.out.println(e);

public class ProducerConsumerExample {

public static void main(String[] args) {

SharedBuffer buffer = new SharedBuffer(5); // Buffer capacity of 5

Producer producer = new Producer(buffer);

Consumer consumer = new Consumer(buffer);

producer.start();

consumer.start();

}
}

Explanation of the Code:

 SharedBuffer Class: Contains a Queue to hold items and methods for producing and
consuming.
o Uses synchronized blocks to ensure thread safety.
o Uses wait() and notify() to manage the buffer's state.
 Producer Class: Extends Thread and produces items in a loop.
 Consumer Class: Extends Thread and consumes items in a loop.
 Main Class: Creates a shared buffer and starts both producer and consumer threads.

OUTPUT:

Produced: 0

Consumed: 0

Produced: 1

Produced: 2

Consumed: 1

...

You might also like