exercise19_7.java

来自「java程序设计 机械工业出版社 书籍代码」· Java 代码 · 共 56 行

JAVA
56
字号
// Exercise19_7.java: Use synchronized set to avoid exception
import java.util.*;

public class Exercise19_7 {
  private Set hashSet = Collections.synchronizedSet(new HashSet());

  class Thread1 extends Thread {
    public void run() {
      for (int i = 0; i < 100; i++) {
        System.out.println("Thread 1");
        hashSet.add(new Integer(i));
        try { Thread.sleep(1000); } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }

  public void xMethod() {
    synchronized (this) {
      // method body
    }
  }

  class Thread2 extends Thread {
    public void run() {
      while (true) {
        System.out.println("Thread 2");
        try { Thread.sleep(1000); } catch (Exception ex) {
          ex.printStackTrace();
        }

        synchronized (hashSet) { // Must synchronize it
          Iterator iterator = hashSet.iterator();

          while (iterator.hasNext()) {
            System.out.println(iterator.next());
          }
        }
      }
    }
  }

  public static void main(String[] args) {
    new Exercise19_7();
  }

  Exercise19_7() {
    Thread1 thread1 = new Thread1();
    Thread2 thread2 = new Thread2();
    thread1.start();
    thread2.start();
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?