Java Lock 重入锁实现多线程顺序打印

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class 重入锁实现ABC循环打印Runnable {
     private static Lock lock = new ReentrantLock();//通过JDK5中的锁来保证线程的访问的互斥
     private static int state = 0;
      
      static class ABCRunnable implements Runnable {
          private String name ;
          private static Map<String,Integer> map = new HashMap<String,Integer>();
          static {
              map.put("A", 0);
              map.put("B", 1);
              map.put("C", 2);
          }
          public ABCRunnable(String name){
              this.name = name;
          }
         public void run() {
             for (int i = 0; i < 10;) {
                 lock.lock();
                 if (state % 3 == map.get(this.name)) {
                     System.out.print(name);
                     state++;  
                      i++;                
                  }
                 lock.unlock();
             }
         }
     }
     
     
     public static void main(String[] args) {
         String[] names = new String[]{"A","B","C"};
         for(int i=0;i<names.length;i++){
             Runnable r = new ABCRunnable(names[i]);
             new Thread(r).start();
         }
     }
     
 }

 

posted @ 2015-10-06 14:58  √珞珈搬砖工√  阅读(365)  评论(0编辑  收藏  举报