java something

          不要以為......很遙遠
          隨筆 - 23, 文章 - 1, 評論 - 2, 引用 - 0
          數據加載中……

          控制3個線程運行順序的Demo

          本程序可以控制3個線程按順序執行, 代碼如下:

          public class Test3 {

           public static void main(String[] args) throws IOException {
            final Test obj = new Test();
            
            new Thread()
            {
             public void run()
             {
              obj.m1();
             }
            }.start();
            new Thread()
            {
             public void run()
             {
              obj.m2();
             }
            }.start();
            new Thread()
            {
             public void run()
             {
              obj.m3();
             }
            }.start();
            
           }

          }

          class Test
          {
           static int count;
           volatile int target = 1;
           synchronized void m1()
           { 
             for (int i = 0; i < 10; i++)
             {
              while (target == 2 || target == 3)
              {
               try {
                wait();
               } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
               }
              }
              System.out.println("m1() =" + i);
              target = 2;
              notifyAll();
             }
           }
           
           synchronized void m2()
           {
            for (int i = 0; i < 10; i++)
            {
             while (target == 1 || target == 3)
             {
              try {
               wait();
              } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
              }
             }
             System.out.println("m2() =" + i);
             target = 3;
             notifyAll();
            }
           }
           
           synchronized void m3()
           {
            for (int i = 0; i < 10; i++)
            {
             while (target == 1 || target == 2)
             {
              try {
               wait();
              } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
              }
             }
             System.out.println("m3() =" + i);
             target = 1;
             notifyAll();
            }
           }
          }

          posted on 2011-09-02 02:27 Jamie 閱讀(1778) 評論(2)  編輯  收藏 所屬分類: 多線程

          評論

          # re: 控制3個線程運行順序的Demo  回復  更多評論   

          類似于信號量.
          2012-08-10 23:24 | zxogj

          # re: 控制3個線程運行順序的Demo  回復  更多評論   

          用retrantLock 也可以把。
          2012-08-10 23:24 | zxogj
          主站蜘蛛池模板: 天全县| 丰城市| 大余县| 平顶山市| 洛宁县| 神池县| 社会| 葵青区| 光山县| 新巴尔虎左旗| 扶沟县| 延长县| 漾濞| 永年县| 溧阳市| 镶黄旗| 永济市| 巴楚县| 金塔县| 肃宁县| 威宁| 沐川县| 临武县| 高要市| 商都县| 兴仁县| 云霄县| 桓仁| 吴忠市| 松潘县| 合肥市| 泾源县| 梅河口市| 阳春市| 新竹市| 和林格尔县| 佛冈县| 衡东县| 江口县| 珠海市| 沐川县|