Java 多线程 synchronized

Java 多线程 synchronized

package thread.sync;

public class NumMake {
  private int i = 0;

  int getNext() {
    return i++;
  }
}
package thread.sync;

public class NumTest {

  /**
   * @author jzh 2011-12-19
   * @param args
   */
  public static void main(String[] args) {
    NumMake num = new NumMake();
    Thread idodoThread = new NumThread("chanpinxue.cn", num);
    Thread jzhThread = new NumThread("jzh", num);
    idodoThread.start();
    jzhThread.start();
  }
}
package thread.sync;

public class NumThread extends Thread {
  private NumMake num;
  private String name;

  public NumThread(String name, NumMake num) {
    super(name);
    this.num = num;
    this.name = name;
  }

  public void run() {
    for (int i = 0; i < 5; i++) {
      synchronized (num) {
        System.out.println(name + " = " + num.getNext());
      }
      try {
        Thread.sleep(200);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}

 

发表回复

您的电子邮箱地址不会被公开。