单项选择题
public class X implements Runnable {
private int x;
private int y;
public static void main(String [] args) {
X that = new X();
(new Thread( that )).start();
(new Thread( that )).start();
}
public void run() {
for (;;) {
synchronized (this) {
x++;
y++;
}
System.out.println(Thread.currentThread().getName() +
“x = “ + x + “, y = “ + y);
}
}
}
What is the result?()
A. Compilation fails.
B. The program prints pairs of values for x and y that might not always be the same on the same line (for example, “x = 2, y = 1”).
C. The program prints pairs of values for x and y that are always the same on the same line (for example, “x = 1, y = 1”). In addition, each value appears only once (for example, “x = 1, y = 1” followed by “x = 2, y = 2”). The thread name at the start of the line shows that both threads are executing concurrently.
D. The program prints pairs of values for x and y that are always the same on the same line (for example, “x = 1, y = 1”). In addition, each value appears only once (for example, “x = 1, y = 1” followed by “x = 2, y = 2”). The thread name at the start of the line shows that only a single thread is actually executing.
相关考题
-
单项选择题
class MyThread extends Thread { public void run() { System.out.println(“AAA”); } public void run(Runnable r) { System.out.println(“BBB”); } public static void main(String[] args) { new Thread(new MyThread()).start(); } } What is the result?()
A. AAA
B. BBB
C. Compilation fails.
D. The code runs with no output. -
单项选择题
WhathappenswhenthreadXexecutesawait()methodonobjectA,withoutowningobjectA’slock?()
A. Compilation fails.
B. An exception is thrown.
C. The wait() method has no effect.
D. Thread X receives the lock immediately.
E. Object A moves the thread to the wait pool. -
单项选择题
public class SyncTest { private int x; private int y; private synchronized void setX( int i ) { x = i; } private synchronized void setY( int i ) { y = i; } public void setXY( int i ) { setX(i); setY(i); } public synchronized boolean check() { return x != y; } } Under which condition will check return true when called from a different class? ()
A. check can never return true.
B. check can return true when setXY is called by multiple threads.
C. check can return true when multiple threads call setX and setY separately.
D. check can return true only if SyncTest is changed to allow x and y to be set separately.
