Java?殻?仟蒙尢-佚催楚
扮寂:2011-02-20 leizhimin
咀緩?云繁範葎?宸倖佚催楚窃泌惚嬬卦指方朕?珊嬬岑祇陳乂斤?壓吉棋?陳乂彿坿辛聞喘?祥掲械頼胆阻?叙叙鎮欺宸乂古凄來議方忖?斤娼鳩陣崙吭吶音頁載寄。朕念珊短?欺厚挫議喘隈。
和中頁匯倖酒汽箭徨?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* Java?殻?仟蒙尢-佚催楚
*
* @author leizhimin
*/
public class Test {
public static void main(String[] args) {
MyPool myPool = new MyPool(20);
//幹秀?殻学
ExecutorService threadPool = Executors.newFixedThreadPool(2);
MyThread t1 = new MyThread("販暦A", myPool, 3);
MyThread t2 = new MyThread("販暦B", myPool, 12);
MyThread t3 = new MyThread("販暦C", myPool, 7);
//壓?殻学嶄峇佩販暦
threadPool.execute(t1);
threadPool.execute(t2);
threadPool.execute(t3);
//購液学
threadPool.shutdown();
}
}
/**
* 匯倖学
*/
class MyPool {
private Semaphore sp; //学?購議佚催楚
/**
* 学議寄弌?宸倖寄弌氏勧弓公佚催楚
*
* @param size 学議寄弌
*/
MyPool(int size) {
this.sp = new Semaphore(size);
}
public Semaphore getSp() {
return sp;
}
public void setSp(Semaphore sp) {
this.sp = sp;
}
}
class MyThread extends Thread {
private String threadname; //?殻議兆各
private MyPool pool; //徭協吶学
private int x; //賦萩佚催楚議寄弌
MyThread(String threadname, MyPool pool, int x) {
this.threadname = threadname;
this.pool = pool;
this.x = x;
}
public void run() {
try {
//貫緩佚催楚資函公協方朕議俯辛
pool.getSp().acquire(x);
//todo?匆俯宸戦辛參恂厚鹸墫議匍暦
System.out.println(threadname + "撹孔資函阻" + x + "倖俯辛?");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//瞥慧公協方朕議俯辛?繍凪卦指欺佚催楚。
pool.getSp().release(x);
System.out.println(threadname + "瞥慧阻" + x + "倖俯辛?");
}
}
}
販暦B撹孔資函阻12倖俯辛?
販暦B瞥慧阻12倖俯辛?
販暦A撹孔資函阻3倖俯辛?
販暦C撹孔資函阻7倖俯辛?
販暦C瞥慧阻7倖俯辛?
販暦A瞥慧阻3倖俯辛?
Process finished with exit code 0
貫潤惚辛參心竃?佚催楚叙叙頁斤学彿坿序佩酌陣?徽音隠屬?殻議芦畠?咀緩?壓聞喘扮昨?哘乎徭失陣崙?殻議芦畠恵諒学彿坿。
竃侃?http://lavasoft.blog.51cto.com/62575/222469 |