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 閱讀(1777) 評論(2)  編輯  收藏 所屬分類: 多線程

          評論

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

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

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

          用retrantLock 也可以把。
          2012-08-10 23:24 | zxogj
          主站蜘蛛池模板: 昌图县| 唐河县| 太谷县| 盈江县| 韶山市| 宾川县| 卓尼县| 牙克石市| 汶川县| 台北县| 吉木萨尔县| 招远市| 灌南县| 全椒县| 江阴市| 将乐县| 土默特右旗| 马龙县| 蒲江县| 徐州市| 陇川县| 信丰县| 榆林市| 宜都市| 隆尧县| 桐梓县| 镇赉县| 沅陵县| 康乐县| 临安市| 四会市| 日土县| 察哈| 金寨县| 长沙县| 林周县| 石嘴山市| 新沂市| 乌拉特前旗| 开平市| 桃江县|