線程學習---對synchronized的測試

          public class myThread extends Thread {
          ?public void run() {
          ??synchronized(System.out){
          ???for (int i = 0; i < 10; i++) {
          ????try{
          ?????sleep(100);
          ????}catch(InterruptedException e){e.printStackTrace();}
          ????
          ????System.out.println(getName() + ": i=" + i);
          ????if (i==9) System.out.println("=========");
          ???}
          ??}
          ?}

          ?public static void main(String[] a) {
          ??myThread thread1 = new myThread();
          ??myThread thread2 = new myThread();
          ??thread1.setName("A");thread1.start();
          ??thread2.setName("B");thread2.start();
          ?}
          }

          在這個測試中,由于執行所需時間片太短,如果不在其中加一句sleep(100)的話,線程A 和線程B的交叉就體現不出來,就更不用說驗證synchronized的作用了; 另,注意synchronized所同步的對象是System.out, 而不是this.

          posted on 2007-05-22 09:34 心硯 閱讀(253) 評論(0)  編輯  收藏 所屬分類: Java

          <2025年7月>
          293012345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          導航

          統計

          常用鏈接

          留言簿(2)

          隨筆分類

          文章分類

          文章檔案

          Forum

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 乌兰察布市| 鄂伦春自治旗| 霍城县| 石台县| 鄂托克前旗| 荔浦县| 绍兴市| 来宾市| 二手房| 锡林浩特市| 镇原县| 通辽市| 乐东| 浮山县| 马边| 肥乡县| 铜山县| 高雄市| 精河县| 宁乡县| 巴东县| 二连浩特市| 闸北区| 礼泉县| 江津市| 方山县| 永胜县| 虎林市| 屏山县| 奈曼旗| 娄底市| 渭南市| 论坛| 五大连池市| 建水县| 安国市| 扎兰屯市| 枞阳县| 襄城县| 华容县| 金沙县|