zoukankan      html  css  js  c++  java
  • 如何控制某个方法允许并发访问线程的个数?

     1  package com.soyoungboy;
     2 
     3  import java.util.concurrent.Semaphore;
     4  /**
     5  *
     6  * @author soyoungboy 2017年1月25日15:51:15
     7  *
     8  */
     9 public class SemaphoreTest {
    10 static Semaphore semaphore = new Semaphore(5,true);
    11  public static void main(String[] args) {
    12  for(int i=0;i<100;i++){
    13  new Thread(new Runnable() {
    14 
    15  @Override
    16  public void run() {
    17  test();
    18  }
    19  }).start();
    20  }
    21 
    22  }
    23 
    24  public static void test(){
    25  try {
    26  //申请一个请求
    27  semaphore.acquire();
    28  } catch (InterruptedException e1) {
    29  e1.printStackTrace();
    30  }
    31  System.out.println(Thread.currentThread().getName()+"进来了");
    32  try {
    33  Thread.sleep(1000);
    34  } catch (InterruptedException e) {
    35  e.printStackTrace();
    36  }
    37  System.out.println(Thread.currentThread().getName()+"走了");
    38  //释放一个请求
    39  semaphore.release();
    40  }
    41  }

    构造函数创建了一个 Semaphore 对象,并且初始化了 5 个信号。这样的效果是控件 test 方法最多只能有 5 个线程并发访问,对于 5 个线程时就排队等待,走一个来一下;

    请求一个信号(消费一个信号),如果信号被用完了则等待;

    释放一个信号,释放的信号新的线程就可以使用了.

  • 相关阅读:
    Python基础之基本数据类型
    Python基础之变量
    mysql数据库
    进程与线程
    并发编程
    网络编程
    内置函数(魔法方法)
    组合,封装,访问限制机制,property装饰器
    面向对象之继承
    Web开发中最致命的8个小错误
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/6349586.html
Copyright © 2011-2022 走看看