Java Intermediate

0% completed

Previous
Next
Quiz
Question 1
What is the main difference between extending the Thread class and implementing the Runnable interface?
A
Extending Thread allows multiple inheritance, while implementing Runnable does not.
B
Implementing Runnable allows the class to extend another class, while extending Thread does not.
C
Extending Thread results in dynamic polymorphism, while Runnable does not support polymorphism.
D
There is no difference; both are identical.
Question 2
What does the join() method do in Java threads?
A
It starts the thread execution.
B
It stops the thread immediately.
C
It pauses the thread for a specified duration.
D
It makes the calling thread wait until the thread on which join() is called completes.
Question 3
Examine the following code snippet that demonstrates thread synchronization:
class Counter {
    private int count = 0;
    public synchronized void increment() {
        count++;
    }
    public int getCount() {
        return count;
    }
}
class MyThread extends Thread {
    private Counter counter;
    MyThread(Counter counter) {
        this.counter = counter;
    }
    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.increment();
        }
    }
}
public class Test {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        MyThread t1 = new MyThread(counter);
        MyThread t2 = new MyThread(counter);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Final count: " + counter.getCount());
    }
}
What is the expected output?
A
Final count: 1000
B
Final count: 2000
C
Final count: less than 2000 due to race conditions.
D
Final count: 0
Question 4
Which of the following thread states indicates that a thread is ready to run and waiting for CPU time?
A
New
B
Blocked
C
Runnable
D
Terminated

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next