Java訊號量控制多執行緒併發
阿新 • • 發佈:2019-02-16
package com.uusafe.thread2;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class UseSinaple {
public static void main(String[] args) {
ExecutorService executorService=Executors.newCachedThreadPool();
final Semaphore eSemaphore=new Semaphore(5);
for (int i = 0; i < 20; i++) {
final int No=i;
Runnable runnable=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
eSemaphore.acquire();
System.out.println("Accessing "+No);
Thread.sleep(10000);
eSemaphore.release();
} catch (Exception e) {
// TODO: handle exception
}
}
};
executorService.execute(runnable);
}
try {
Thread.sleep(3000);
} catch (Exception e) {
// TODO: handle exception
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class UseSinaple {
public static void main(String[] args) {
ExecutorService executorService=Executors.newCachedThreadPool();
final Semaphore eSemaphore=new Semaphore(5);
for (int i = 0; i < 20; i++) {
final int No=i;
Runnable runnable=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
eSemaphore.acquire();
System.out.println("Accessing "+No);
Thread.sleep(10000);
eSemaphore.release();
} catch (Exception e) {
// TODO: handle exception
}
}
};
executorService.execute(runnable);
}
try {
Thread.sleep(3000);
} catch (Exception e) {
// TODO: handle exception
}
}
}