package cn.yb.thread;
import java.util.concurrent.Semaphore;
public class WorkerMachineDemo {
static class Work implements Runnable{
private int workerNum;
private Semaphore semaphore;
public Work(int workerNum,Semaphore semaphore) {
this.workerNum = workerNum;
this.semaphore = semaphore;
}
public void run() {
try {
semaphore.acquire();
String name = Thread.currentThread().getName();
System.out.println("获取到机器,开始工作。。。"+name);
Thread.sleep(1000);
semaphore.release();
System.out.println(name+"使用完毕,释放机器!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
int workers = 8;
Semaphore semaphore = new Semaphore(3);
for(int i = 0;i<workers;i++) {
new Thread(new Work(i, semaphore)).start();
}
}
}
