多線程同步

package thread;
/**
*    
* synchronized關鍵字實現多線程同步
*(1)靜態變量爲所有對象共享,可以對其加鎖,實現在同步
*(2)靜態方法加鎖,鎖住的是類,也可實現同步
*/

public class PrintNum implements Runnable
{
  private int id;
    
  private static Object lock = new Object();

  public PrintNum(int id)
  {
    this.id = id;
  }

//  方法1:對靜態變量加鎖
//  public void run()
//  {
//
//     synchronized (lock)
//     {
//      for (int i = 0; i < 100; i++)
//      {
//
//        System.out.println("Thread-" + id + ":" + i);
//        }
//    }
//
//  }
  //方法2:對靜態方法加鎖
  public     void run()
  {
      taskHandler(id);
  }
  synchronized public static void taskHandler(int id)
  {
    for (int i = 0; i < 100; i++)
    {

      System.out.println("Thread-" + id + ":" + i);
      }
  }
  public static void main(String args[])
  {

    for (int i = 0; i < 10; i++)
    {
      new Thread(new PrintNum(i)).start();
      //the flowing code just for test
      for(int j = 1;j<10;j++)
      {
        if(j==9)
        {
          System.out.println("wait me for a while...");
        }
      }
    }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章