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 阅读(1748) 评论(2)  编辑  收藏 所属分类: 多线程

评论

# re: 控制3个线程运行顺序的Demo  回复  更多评论   

类似于信号量.
2012-08-10 23:24 | zxogj

# re: 控制3个线程运行顺序的Demo  回复  更多评论   

用retrantLock 也可以把。
2012-08-10 23:24 | zxogj

只有注册用户登录后才能发表评论。


网站导航: