---
title: "Concurrent - Semaphore - Async & Sync"
author: "fairy_xzc"
date: "2016-12-06T15:39:46Z"
tags: []
categories: ["编程语言"]
slug: "concurrent-semaphore-async-sync"
draft: false
lastmod: "2016-12-06T15:36:46Z"
id: 2343157
url: "https://agilestyle.iteye.com/blog/2343157"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2343157](/blog/2343157)**

 

## 异步即无阻塞

Service.java

```
package org.fool.java.concurrent.semaphore.async;

import java.util.concurrent.Semaphore;

public class Service {
    private Semaphore semaphore = new Semaphore(3);

    public void testMethod() {
        try {
            semaphore.acquire();

            System.out.println(Thread.currentThread().getName() + " start");

            System.out.println("begin " + System.currentTimeMillis());

            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " print " + (i + 1));
            }

            System.out.println("end " + System.currentTimeMillis());

            System.out.println(Thread.currentThread().getName() + " end");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}
```

ThreadA.java

```
package org.fool.java.concurrent.semaphore.async;

public class ThreadA implements Runnable {
    private Service service;

    public ThreadA(Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.testMethod();
    }
}
```

AsyncTest.java

```
package org.fool.java.concurrent.semaphore.async;

public class AsyncTest {
    public static void main(String[] args) {
        Service service = new Service();

        for(int i = 0; i < 10; i++) {
            new Thread(new ThreadA(service)).start();
        }
    }
}
```

Run

![](http://dl2.iteye.com/upload/attachment/0121/7875/9cc9528d-0562-3869-8a58-bd03e661dff4.png)  
Note:

运行的效果是多个线程同时进入，多个线程又几乎同时执行完毕，一瞬间的事情，打印循环中的内容为乱序。 

 

## 同步即有阻塞

Service.java

```
package org.fool.java.concurrent.semaphore.sync;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

public class Service {
    private Semaphore semaphore = new Semaphore(3);
    private ReentrantLock lock = new ReentrantLock();

    public void testMethod() {
        try {
            semaphore.acquire();

            System.out.println(Thread.currentThread().getName() + " start");

            lock.lock();
            System.out.println("begin " + System.currentTimeMillis());

            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " print " + (i + 1));
            }

            System.out.println("end " + System.currentTimeMillis());

            lock.unlock();

            System.out.println(Thread.currentThread().getName() + " end");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}
```

ThreadA.java

```
package org.fool.java.concurrent.semaphore.sync;

public class ThreadA implements Runnable {
    private Service service;

    public ThreadA(Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.testMethod();
    }
}
```

SyncTest.java

```
package org.fool.java.concurrent.semaphore.sync;

public class SyncTest {
    public static void main(String[] args) {
        Service service = new Service();

        for(int i = 0; i < 10; i++) {
            new Thread(new ThreadA(service)).start();
        }
    }
}
```

Run

![](http://dl2.iteye.com/upload/attachment/0121/7877/d8857113-35b2-3175-8d28-9786c9321fcd.png)  
Note:

在代码中加入了ReentrantLock，保证了同步性， 打印循环中的内容为有序。