public class ThreadPoolTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 1; i <=10 ; i++) {
final int task = i;
executorService.execute(new Runnable() {
@Override
public void run() {
for (int j = 1; j <= 10; j++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is for " + " j= " + j +" task = " + task);
}
}
});
}
//executorService.shutdown();
}
}
代碼很簡單就不解釋了
看一下第二種方式
public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final Semaphore s = new Semaphore(3);
for (int i = 0; i < 10; i++) {// 開是個對象
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
s.acquire();// 判斷對象的信号燈,亮就代表有線程
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("線程" + Thread.currentThread() + "進入,目前已有" + s.availablePermits());
try {
Thread.sleep((long)(Math.random()*10000));
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("線程"+Thread.currentThread()+"即将離開");
s.release();
System.out.println("線程"+Thread.currentThread()+"線程已離開,目前已有"+s.availablePermits());
}
};
service.execute(runnable);// 把對象裝線程池
}
}
}