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();
         }
     }
     
 }

 

    原文作者:√珞珈搬砖工√
    原文地址: https://www.cnblogs.com/Jote/articles/4857146.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞