2017年9月17日 | Leave a comment 问题 解决: //SemaphoreTest.java //javac SemaphoreTest.java && java SemaphoreTest import java.util.concurrent.*; import java.util.*; class SemaphoreTest{ public static void main(String[] argv){ Semaphore s = new Semaphore(2); for(int i=0;i<10;i++){ Thread t = new Thread(()->{ for(int j = 0 ;j<3; ++j){ try{ s.acquire(); System.out.println(Thread.currentThread().getName()+" j : "+j); Thread.sleep(1000); s.release(); }catch(Exception e){} } }); t.setName("ppthread"+i); t.start(); } System.out.println("main end"); } } 12345678910111213141516171819202122232425 //SemaphoreTest.java//javac SemaphoreTest.java && java SemaphoreTestimport java.util.concurrent.*;import java.util.*; class SemaphoreTest{ public static void main(String[] argv){ Semaphore s = new Semaphore(2); for(int i=0;i<10;i++){ Thread t = new Thread(()->{ for(int j = 0 ;j<3; ++j){ try{ s.acquire(); System.out.println(Thread.currentThread().getName()+" j : "+j); Thread.sleep(1000); s.release(); }catch(Exception e){} } }); t.setName("ppthread"+i); t.start(); } System.out.println("main end"); }} 参考: