原文地址: http://www.java2000.net/p11622
上次使用了自己设计的结构,实现了一个方法,只能被2个线程同时使用
一个方法最多2个线程同时使用的JAVA实现
经网友提醒,发现用信号量才是正途,我这里只给出测试代码和运行效果,其它的大家自己看吧- package concurrent;
- import java.util.concurrent.Semaphore;
- /**
- * 信号量,实现方法的多线程限量使用。
- *
- * @author 老紫竹 JAVA世纪网(java2000.net)
- *
- */
- public class SemaphoreTest extends Thread {
- public static void main(String[] args) {
- for (int i = 0; i <= 10; i++) {
- new SemaphoreTest().start();
- }
- }
- public void run() {
- int i = 2;
- OnlyTwo ot = new OnlyTwo();
- while (i-- > 0) {
- System.out.printf("[%3d]%d=%d/n",this.getId(),System.currentTimeMillis(),+ot.getSomthing());
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- ot.returnSomthing();
- }
- }
- }
- class OnlyTwo {
- private static final int MAX_AVAILABLE = 3;
- private static final Semaphore available = new Semaphore(MAX_AVAILABLE, false);
- private static int NUM = 1;
- /**
- * 执行方法。
- *
- * @return
- */
- public int getSomthing() {
- try {
- available.acquire();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return NUM++;
- }
- /**
- * 归还
- */
- public void returnSomthing() {
- available.release();
- }
- }
运行效果
[ 9]1225837305234=1
[ 10]1225837305250=3
[ 8]1225837305250=2
[ 8]1225837305468=4
[ 10]1225837305468=6
[ 9]1225837305468=5
[ 12]1225837305250=7
[ 14]1225837305250=8
[ 16]1225837305250=9
[ 16]1225837305875=10
[ 12]1225837305875=12
[ 14]1225837305875=11
[ 18]1225837305250=13
[ 13]1225837305250=15
[ 11]1225837305250=14
[ 18]1225837306281=16
[ 13]1225837306281=18
[ 11]1225837306281=17
[ 15]1225837305250=19
[ 17]1225837305250=20
[ 17]1225837306687=21
[ 15]1225837306687=22