Semaphore 是 synchronized 的加强版,作用是控制线程的并发数量。
示例:
MyThread.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class MyThread extends Thread{
private String name; private SemaphoreService service;
public MyThread(String name, SemaphoreService service) { super(); this.name = name; this.service = service; }
@Override public void run() { this.service.doSomething(); } }
|
SemaphoreService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Semaphore;
public class SemaphoreService { private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private Semaphore semaphore = new Semaphore(2);
public void doSomething() { try {
semaphore.acquire(); System.out.println(Thread.currentThread().getName() + ":doSomething start-" + getFormatTimeStr()); Thread.sleep(2000); System.out.println(Thread.currentThread().getName() + ":doSomething end-" + getFormatTimeStr()); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } }
public static String getFormatTimeStr() { return sf.format(new Date()); } }
|
SemaphoreTest.java
1 2 3 4 5 6 7 8 9 10
| public class SemaphoreTest {
public static void main(String args[]) { SemaphoreService service = new SemaphoreService(); for (int i = 0; i < 10; i++) { MyThread t = new MyThread("thread" + (i + 1), service); t.start(); } } }
|