Given:
1. public class TwoThreads {
2
3. private static Object resource = new Object();
4.
5. private static void delay(long n) {
6. try { Thread.sleep(n); }
7. catch (Exception e) { System.out.print(”Error “); }
8. }
9
10. public static void main(String[] args) {
11. System.out.print(”StartMain “);
12. new Thread1().start();
13. delay(1000);
14. Thread t2 = new Thread2();
15. t2.start();
16. delay(1000);
17. t2.interrupt
18. delay(1000);
19. System.out.print(”EndMain “);
20. }
21.
22. static class Thread 1 extends Thread {
23. public void run() {
24. synchronized (resource) {                                              //resource什么意思????
25. System.out.print(”Startl “);
26. delay(6000);
27. System.out.print(”End1 “);
28. }
29. }
30. }
31.
32. static class Thread2 extends Thread {
33. public void run() {
34. synchronized (resource) {
35. System.out.print(”Start2 “);
36. delay(2000);
37. System.out.print(”End2 “);
38. }
39. }
40. }
41. }
Assume that sleep(n) executes in exactly m milliseconds, and all other
code executes in an insignificant amount of time. What is the output if
the main() method is run?
A. Compilation fails.
B. Deadlock occurs.
C. StartMain Start1 Error EndMain End1
D. StartMain Start1 EndMain End1 Start2 End2
E. StartMain Start1 Error Start2 EndMain End2 End1
F. StartMain Start1 Start2 Error End2 EndMain End1
G. StartMain Start1 EndMain End1 Start2 Error End2
答案是G,希望大侠能详细指点~^_^
顺路问一下,synchronized (resource):这里的resource是什么意思?- -

解决方案 »

  1.   

    synchronized (resource):此处应该是对resource对象实行同步,也就是{}中的代码实行同步操作。
      

  2.   

    resource不是private static Object resource = new Object(); 这个东西吗
      

  3.   

    就是操作系统中的一个锁的概念,在每个线程进入synchronized段之前,都要先取得锁才能进入这个临界区,执行完这个synchronized段会自动释放锁,已达到线程同步的目的。
      

  4.   


    额 锁的概念是了解了。
    这样其他顺序都清楚了,只是Error……其实是interrupt()搞不懂……这个Java Doc上讲的好抽象,貌似interrupt()之后再sleep()就抛出错误了?为什么?- -