MCQs
(2) is correct because wait() always causes the current thread to go into the object's wait pool.
(5) is correct because sleep() will always pause the currently running thread for at least the
duration specified in the sleep argument (unless an interrupted exception is thrown).
(6) is correct because, assuming that the thread you're calling join() on is alive, the thread calling
join() will immediately block until the thread you're calling join() on is no longer alive.
(1) is wrong, but tempting. The yield() method is not guaranteed to cause a thread to leave the
running state, although if there are runnable threads of the same priority as the currently running
thread, then the current thread will probably leave the running state.
(3) and (4) are incorrect because they don't cause the thread invoking them to leave the running state.
(7) is wrong because there's no such method.
What is the output of this program?
class newthread extends Thread {
Thread t;
String name;
newthread(String threadname) {
name = threadname;
t = new Thread(this,name);
t.start();
}
public void run() {
}
}
class multithreaded_programing {
public static void main(String args[]) {
newthread obj1 = new newthread("one");
newthread obj2 = new newthread("two");
try {
obj1.t.wait();
System.out.print(obj1.t.isAlive());
}
catch(Exception e) {
System.out.print("Main thread interrupted");
}
}
}
obj1.t.wait() causes main thread to go out of processing in sleep state hence causes
exception and "Main thread interrupted" is printed.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Main thread interrupted
(1) and (4). Only start() and run() are defined by the Thread class.
(2) and (3) are incorrect because they are methods of the Object class. (5) is incorrect
because there's no such method in any thread-related class.
When two or more threads need to access the same shared resource, they need
some way to ensure that the resource will be used by only one thread at a time, the
process by which this is achieved is called synchronization
Option C is correct. notify() - wakes up a single thread that is waiting on this object's monitor.
None.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
My Thread
When two or more threads need to access the same shared resource, they need some
way to ensure that the resource will be used by only one thread at a time, the process by
which this is achieved is called synchronization
The default value of priority given to a thread is 5 but we can explicitly change that value
between the permitted values 1 & 10, this is done by using the method setPriority().
notifyAll() wakes up all the threads that called wait() on the same object. The highest
Option C is suitable to start a thread.