Java Programming - Threads
- Threads - General Questions
- Threads - Finding the output
- Threads - Pointing out the correct statements
public class Test107 implements Runnable
{
private int x;
private int y;
public static void main(String args[])
{
Test107 that = new Test107();
(new Thread(that)).start();
(new Thread(that)).start();
}
public synchronized void run()
{
for(int i = 0; i < 10; i++)
{
x++;
y++;
System.out.println("x = " + x + ", y = " + y); /* Line 17 */
}
}
}
Both threads are operating on the same instance variables. Because the code is synchronized the first thread will complete before the second thread begins. Modify line 17 to print the thread names:
System.out.println(Thread.currentThread().getName() + " x = " + x + ", y = " + y);
public class Test
{
public static void main (String [] args)
{
final Foo f = new Foo();
Thread t = new Thread(new Runnable()
{
public void run()
{
f.doStuff();
}
});
Thread g = new Thread()
{
public void run()
{
f.doStuff();
}
};
t.start();
g.start();
}
}
class Foo
{
int x = 5;
public void doStuff()
{
if (x < 10)
{
// nothing to do
try
{
wait();
} catch(InterruptedException ex) { }
}
else
{
System.out.println("x is " + x++);
if (x >= 10)
{
notify();
}
}
}
}
C is correct because the thread does not own the lock of the object it invokes wait() on. If the method were synchronized, the code would run without exception.
A, B are incorrect because the code compiles without errors.
D is incorrect because the exception is thrown before there is any output.
class MyThread extends Thread
{
public static void main(String [] args)
{
MyThread t = new MyThread();
Thread x = new Thread(t);
x.start(); /* Line 7 */
}
public void run()
{
for(int i = 0; i < 3; ++i)
{
System.out.print(i + "..");
}
}
}
The thread MyThread will start and loop three times (from 0 to 2).
Option A is incorrect because the Thread class implements the Runnable interface; therefore, in line 7, Thread can take an object of type Thread as an argument in the constructor.
Option B and C are incorrect because the variable i in the for loop starts with a value of 0 and ends with a value of 2.