1. class EvenOddPrinter {
    2. public static void main(String[] args) throws Exception {
    3. R r = new R();
    4. new Thread("偶数线程") {
    5. @Override
    6. public void run() {
    7. while (r.v < 100) {
    8. try {
    9. r.printOdd();
    10. } catch (Exception e) {
    11. e.printStackTrace();
    12. }
    13. }
    14. }
    15. }.start();
    16. new Thread("奇数线程") {
    17. @Override
    18. public void run() {
    19. while (r.v < 100) {
    20. try {
    21. r.printEven();
    22. } catch (Exception e) {
    23. e.printStackTrace();
    24. }
    25. }
    26. }
    27. }.start();
    28. }
    29. static class R {
    30. private int v = 0;
    31. private Object lock = new Object();
    32. synchronized void printEven() throws Exception {
    33. if (v % 2 != 0) {
    34. System.out.println(Thread.currentThread().getName() + ":" + v++);
    35. notifyAll();
    36. wait();
    37. }
    38. }
    39. synchronized void printOdd() throws Exception {
    40. if (v % 2 == 0) {
    41. System.out.println(Thread.currentThread().getName() + ":" + v++);
    42. notifyAll();
    43. wait();
    44. }
    45. }
    46. }
    47. }