Maison  >  Article  >  Java  >  Exemples de concurrence Java CountDownLatch, CyclicBarrier et Semaphore

Exemples de concurrence Java CountDownLatch, CyclicBarrier et Semaphore

黄舟
黄舟original
2017-09-20 10:30:271212parcourir

Cet article présente principalement la programmation simultanée Java : exemples CountDownLatch, CyclicBarrier et Semaphore. Les amis qui en ont besoin peuvent se référer à

Programmation simultanée Java : CountDownLatch, CyclicBarrier et Semaphore. >

Dans Java 1.5, certaines classes auxiliaires très utiles sont fournies pour nous aider dans la programmation simultanée, telles que CountDownLatch, CyclicBarrier et Semaphore. Aujourd'hui, nous allons découvrir l'utilisation de ces trois classes auxiliaires.

Ce qui suit est le aperçu de la table des matières de cet article :

1. Utilisation de CountDownLatch 2. Utilisation de CyclicBarrier
3. Utilisation du sémaphore

Veuillez me pardonner s'il y a des inexactitudes et acceptez les critiques et les corrections.

1. Utilisation de CountDownLatch

La classe CountDownLatch est située sous le package java.util.concurrent, qui peut être utilisée pour implémenter des fonctions de type compteur. Par exemple, il existe une tâche A qui doit attendre la fin des quatre autres tâches avant de pouvoir être exécutée. À ce stade, vous pouvez utiliser CountDownLatch pour implémenter cette fonction.

La classe CountDownLatch ne fournit qu'un seul constructeur :


public CountDownLatch(int count) { }; //参数count为计数值
Ensuite, les trois méthodes suivantes sont les méthodes les plus importantes de la classe CountDownLatch :


public void await() throws InterruptedException { };  //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { }; //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public void countDown() { }; //将count值减1
Regardez un exemple ci-dessous pour comprendre l'utilisation de CountDownLatch :


public class Test {
   public static void main(String[] args) {  
     final CountDownLatch latch = new CountDownLatch(2);

     new Thread(){
       public void run() {
         try {
           System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
          Thread.sleep(3000);
          System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
          latch.countDown();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
       };
     }.start();

     new Thread(){
       public void run() {
         try {
           System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
           Thread.sleep(3000);
           System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
           latch.countDown();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
       };
     }.start();

     try {
       System.out.println("等待2个子线程执行完毕...");
      latch.await();
      System.out.println("2个子线程已经执行完毕");
      System.out.println("继续执行主线程");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
   }
}
Résultat de l'exécution :


线程Thread-0正在执行
线程Thread-1正在执行
等待2个子线程执行完毕...
线程Thread-0执行完毕
线程Thread-1执行完毕
2个子线程已经执行完毕
继续执行主线程

2. Utilisation de CyclicBarrier

Signifie littéralement une barrière de boucle, à travers laquelle un groupe de threads peut attendre après avoir atteint un certain état, ils sont tous exécutés en même temps. C'est ce qu'on appelle le bouclage car CyclicBarrier peut être réutilisé une fois que tous les threads en attente sont libérés. Appelons cette barrière d'état pour le moment. Lorsque la méthode wait() est appelée, le thread est en barrière.

La classe CyclicBarrier se trouve sous le package java.util.concurrent CyclicBarrier fournit 2 constructeurs :


public CyclicBarrier(int parties, Runnable barrierAction) {
}

public CyclicBarrier(int parties) {
}
Le paramètre parties fait référence au nombre de parties. threads ou La tâche attend l'état barrière ; le paramètre barrièreAction est ce qui sera exécuté lorsque ces threads atteindront l'état barrière.

Ensuite, la méthode la plus importante dans CyclicBarrier est la méthode wait, qui a 2 versions surchargées :


public int await() throws InterruptedException, BrokenBarrierException { };
public int await(long timeout, TimeUnit unit)throws InterruptedException,BrokenBarrierException,TimeoutException { };
La première version est plus couramment utilisée, Utilisé pour suspendre le thread actuel jusqu'à ce que tous les threads atteignent l'état de barrière, puis exécuter les tâches suivantes en même temps

La deuxième version consiste à laisser ces threads attendre un certain temps s'il y a encore des threads qui l'ont fait. n'a pas atteint l'état de barrière, laissez directement le thread qui atteint la barrière effectuer les tâches suivantes.

Quelques exemples vous aideront à comprendre :

Supposons qu'il y ait plusieurs threads qui doivent écrire des données, et seulement après que tous les threads ont terminé l'opération d'écriture des données, ces threads peuvent continuer à faire le suivant A ce moment, vous pouvez utiliser CyclicBarrier :


public class Test {
  public static void main(String[] args) {
    int N = 4;
    CyclicBarrier barrier = new CyclicBarrier(N);
    for(int i=0;i<N;i++)
      new Writer(barrier).start();
  }
  static class Writer extends Thread{
    private CyclicBarrier cyclicBarrier;
    public Writer(CyclicBarrier cyclicBarrier) {
      this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
      System.out.println("线程"+Thread.currentThread().getName()+"正在写入数据...");
      try {
        Thread.sleep(5000);   //以睡眠来模拟写入数据操作
        System.out.println("线程"+Thread.currentThread().getName()+"写入数据完毕,等待其他线程写入完毕");
        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }catch(BrokenBarrierException e){
        e.printStackTrace();
      }
      System.out.println("所有线程写入完毕,继续处理其他任务...");
    }
  }
}
Résultat de l'exécution :


线程Thread-0正在写入数据...
线程Thread-3正在写入数据...
线程Thread-2正在写入数据...
线程Thread-1正在写入数据...
线程Thread-2写入数据完毕,等待其他线程写入完毕
线程Thread-0写入数据完毕,等待其他线程写入完毕
线程Thread-3写入数据完毕,等待其他线程写入完毕
线程Thread-1写入数据完毕,等待其他线程写入完毕
所有线程写入完毕,继续处理其他任务...
所有线程写入完毕,继续处理其他任务...
所有线程写入完毕,继续处理其他任务...
所有线程写入完毕,继续处理其他任务...
Il Le résultat ci-dessus montre qu'une fois que chaque thread d'écriture a terminé l'opération d'écriture de données, il attend que d'autres threads terminent l'opération d'écriture.

Une fois toutes les opérations d'écriture de thread terminées, tous les threads continueront à effectuer les opérations suivantes.

Si vous souhaitez effectuer des opérations supplémentaires une fois que tous les threads ont terminé les opérations d'écriture, vous pouvez fournir des paramètres Runnable pour CyclicBarrier :


public class Test {
  public static void main(String[] args) {
    int N = 4;
    CyclicBarrier barrier = new CyclicBarrier(N,new Runnable() {
      @Override
      public void run() {
        System.out.println("当前线程"+Thread.currentThread().getName());  
      }
    });

    for(int i=0;i<N;i++)
      new Writer(barrier).start();
  }
  static class Writer extends Thread{
    private CyclicBarrier cyclicBarrier;
    public Writer(CyclicBarrier cyclicBarrier) {
      this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
      System.out.println("线程"+Thread.currentThread().getName()+"正在写入数据...");
      try {
        Thread.sleep(5000);   //以睡眠来模拟写入数据操作
        System.out.println("线程"+Thread.currentThread().getName()+"写入数据完毕,等待其他线程写入完毕");
        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }catch(BrokenBarrierException e){
        e.printStackTrace();
      }
      System.out.println("所有线程写入完毕,继续处理其他任务...");
    }
  }
}
Résultats d'exécution :


线程Thread-0正在写入数据...
线程Thread-1正在写入数据...
线程Thread-2正在写入数据...
线程Thread-3正在写入数据...
线程Thread-0写入数据完毕,等待其他线程写入完毕
线程Thread-1写入数据完毕,等待其他线程写入完毕
线程Thread-2写入数据完毕,等待其他线程写入完毕
线程Thread-3写入数据完毕,等待其他线程写入完毕
当前线程Thread-3
所有线程写入完毕,继续处理其他任务...
所有线程写入完毕,继续处理其他任务...
所有线程写入完毕,继续处理其他任务...
所有线程写入完毕,继续处理其他任务...
Comme le montrent les résultats, lorsque les quatre threads atteignent l'état barrière, un thread sera sélectionné parmi les quatre threads pour exécuter Runnable.

Jetons un coup d'œil à l'effet de la spécification du temps d'attente :


public class Test {
  public static void main(String[] args) {
    int N = 4;
    CyclicBarrier barrier = new CyclicBarrier(N);

    for(int i=0;i<N;i++) {
      if(i<N-1)
        new Writer(barrier).start();
      else {
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        new Writer(barrier).start();
      }
    }
  }
  static class Writer extends Thread{
    private CyclicBarrier cyclicBarrier;
    public Writer(CyclicBarrier cyclicBarrier) {
      this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
      System.out.println("线程"+Thread.currentThread().getName()+"正在写入数据...");
      try {
        Thread.sleep(5000);   //以睡眠来模拟写入数据操作
        System.out.println("线程"+Thread.currentThread().getName()+"写入数据完毕,等待其他线程写入完毕");
        try {
          cyclicBarrier.await(2000, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }catch(BrokenBarrierException e){
        e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName()+"所有线程写入完毕,继续处理其他任务...");
    }
  }
}
Résultats d'exécution :


线程Thread-0正在写入数据...
线程Thread-2正在写入数据...
线程Thread-1正在写入数据...
线程Thread-2写入数据完毕,等待其他线程写入完毕
线程Thread-0写入数据完毕,等待其他线程写入完毕
线程Thread-1写入数据完毕,等待其他线程写入完毕
线程Thread-3正在写入数据...
java.util.concurrent.TimeoutException
Thread-1所有线程写入完毕,继续处理其他任务...
Thread-0所有线程写入完毕,继续处理其他任务...
  at java.util.concurrent.CyclicBarrier.dowait(Unknown Source)
  at java.util.concurrent.CyclicBarrier.await(Unknown Source)
  at com.cxh.test1.Test$Writer.run(Test.java:58)
java.util.concurrent.BrokenBarrierException
  at java.util.concurrent.CyclicBarrier.dowait(Unknown Source)
  at java.util.concurrent.CyclicBarrier.await(Unknown Source)
  at com.cxh.test1.Test$Writer.run(Test.java:58)
java.util.concurrent.BrokenBarrierException
  at java.util.concurrent.CyclicBarrier.dowait(Unknown Source)
  at java.util.concurrent.CyclicBarrier.await(Unknown Source)
  at com.cxh.test1.Test$Writer.run(Test.java:58)
Thread-2所有线程写入完毕,继续处理其他任务...
java.util.concurrent.BrokenBarrierException
线程Thread-3写入数据完毕,等待其他线程写入完毕
  at java.util.concurrent.CyclicBarrier.dowait(Unknown Source)
  at java.util.concurrent.CyclicBarrier.await(Unknown Source)
  at com.cxh.test1.Test$Writer.run(Test.java:58)
Thread-3所有线程写入完毕,继续处理其他任务...
Le code ci-dessus retarde délibérément le début du dernier thread dans la boucle for de la méthode principale, car une fois que les trois premiers threads ont atteint la barrière, ils ont attendu le temps spécifié et ont constaté que le quatrième le thread n'a pas encore atteint la barrière. Lancez simplement une exception et continuez à effectuer les tâches suivantes.

De plus, CyclicBarrier peut être réutilisé, voir l'exemple suivant :


/**
 * Java学习交流QQ群:589809992 我们一起学Java!
 */
public class Test {
  public static void main(String[] args) {
    int N = 4;
    CyclicBarrier barrier = new CyclicBarrier(N);

    for(int i=0;i<N;i++) {
      new Writer(barrier).start();
    }

    try {
      Thread.sleep(25000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("CyclicBarrier重用");

    for(int i=0;i<N;i++) {
      new Writer(barrier).start();
    }
  }
  static class Writer extends Thread{
    private CyclicBarrier cyclicBarrier;
    public Writer(CyclicBarrier cyclicBarrier) {
      this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
      System.out.println("线程"+Thread.currentThread().getName()+"正在写入数据...");
      try {
        Thread.sleep(5000);   //以睡眠来模拟写入数据操作
        System.out.println("线程"+Thread.currentThread().getName()+"写入数据完毕,等待其他线程写入完毕");

        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }catch(BrokenBarrierException e){
        e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName()+"所有线程写入完毕,继续处理其他任务...");
    }
  }
}
Résultat de l'exécution :


线程Thread-0正在写入数据...
线程Thread-1正在写入数据...
线程Thread-3正在写入数据...
线程Thread-2正在写入数据...
线程Thread-1写入数据完毕,等待其他线程写入完毕
线程Thread-3写入数据完毕,等待其他线程写入完毕
线程Thread-2写入数据完毕,等待其他线程写入完毕
线程Thread-0写入数据完毕,等待其他线程写入完毕
Thread-0所有线程写入完毕,继续处理其他任务...
Thread-3所有线程写入完毕,继续处理其他任务...
Thread-1所有线程写入完毕,继续处理其他任务...
Thread-2所有线程写入完毕,继续处理其他任务...
CyclicBarrier重用
线程Thread-4正在写入数据...
线程Thread-5正在写入数据...
线程Thread-6正在写入数据...
线程Thread-7正在写入数据...
线程Thread-7写入数据完毕,等待其他线程写入完毕
线程Thread-5写入数据完毕,等待其他线程写入完毕
线程Thread-6写入数据完毕,等待其他线程写入完毕
线程Thread-4写入数据完毕,等待其他线程写入完毕
Thread-4所有线程写入完毕,继续处理其他任务...
Thread-5所有线程写入完毕,继续处理其他任务...
Thread-6所有线程写入完毕,继续处理其他任务...
Thread-7所有线程写入完毕,继续处理其他任务...
Les résultats d'exécution montrent qu'une fois que les quatre premiers threads ont traversé l'état barrière, ils peuvent être utilisés pour un nouveau cycle d'utilisation. CountDownLatch ne peut pas être réutilisé.

3. Utilisation du sémaphore

Sémaphore est traduit littéralement par sémaphore peut contrôler le nombre de threads accessibles en même temps et en obtenir un via l'acquisition. (), attendez s'il n'est pas disponible et release() libère une autorisation.

La classe Semaphore se trouve sous le package java.util.concurrent Elle fournit 2 constructeurs :


public Semaphore(int permits) {     //参数permits表示许可数目,即同时可以允许多少线程进行访问
  sync = new NonfairSync(permits);
}
public Semaphore(int permits, boolean fair) {  //这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可
  sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
}
Parlons de la comparaison dans le Classe sémaphore Plusieurs méthodes importantes, tout d'abord, sont les méthodes acquire() et release() :


public void acquire() throws InterruptedException { }   //获取一个许可
public void acquire(int permits) throws InterruptedException { }  //获取permits个许可
public void release() { }     //释放一个许可
public void release(int permits) { }  //释放permits个许可
acquire() est utilisée pour obtenir une licence If. il n'y a pas de licence, elle peut être obtenue en attendant l'obtention de l'autorisation.

release() est utilisé pour libérer la licence. Notez que l’autorisation doit être obtenue avant de pouvoir être publiée.

Ces quatre méthodes seront bloquées. Si vous souhaitez obtenir le résultat de l'exécution immédiatement, vous pouvez utiliser les méthodes suivantes :


public boolean tryAcquire() { };  //尝试获取一个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { }; //尝试获取一个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
public boolean tryAcquire(int permits) { }; //尝试获取permits个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException { }; //尝试获取permits个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false

另外还可以通过availablePermits()方法得到可用的许可数目。

下面通过一个例子来看一下Semaphore的具体使用:

假若一个工厂有5台机器,但是有8个工人,一台机器同时只能被一个工人使用,只有使用完了,其他工人才能继续使用。那么我们就可以通过Semaphore来实现:


/**
 * Java学习交流QQ群:589809992 我们一起学Java!
 */
public class Test {
  public static void main(String[] args) {
    int N = 8;      //工人数
    Semaphore semaphore = new Semaphore(5); //机器数目
    for(int i=0;i<N;i++)
      new Worker(i,semaphore).start();
  }

  static class Worker extends Thread{
    private int num;
    private Semaphore semaphore;
    public Worker(int num,Semaphore semaphore){
      this.num = num;
      this.semaphore = semaphore;
    }

    @Override
    public void run() {
      try {
        semaphore.acquire();
        System.out.println("工人"+this.num+"占用一个机器在生产...");
        Thread.sleep(2000);
        System.out.println("工人"+this.num+"释放出机器");
        semaphore.release();      
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

执行结果:


工人0占用一个机器在生产...
工人1占用一个机器在生产...
工人2占用一个机器在生产...
工人4占用一个机器在生产...
工人5占用一个机器在生产...
工人0释放出机器
工人2释放出机器
工人3占用一个机器在生产...
工人7占用一个机器在生产...
工人4释放出机器
工人5释放出机器
工人1释放出机器
工人6占用一个机器在生产...
工人3释放出机器
工人7释放出机器
工人6释放出机器

下面对上面说的三个辅助类进行一个总结:

1)CountDownLatch和CyclicBarrier都能够实现线程之间的等待,只不过它们侧重点不同:

CountDownLatch一般用于某个线程A等待若干个其他线程执行完任务之后,它才执行; 而CyclicBarrier一般用于一组线程互相等待至某个状态,然后这一组线程再同时执行; 另外,CountDownLatch是不能够重用的,而CyclicBarrier是可以重用的。

2)Semaphore其实和锁有点类似,它一般用于控制对某组资源的访问权限。

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn