62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.concurrent.Semaphore;
public class Test
{
public static void main(String[] args)
{
Semaphore semaphore = new Semaphore(0);
for (int i = 0; i < 10; i++)
{
new TestThread(i, semaphore).start();
}
try
{
semaphore.acquire(10); //需要10个信号量才能继续
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("finished!");
}
}
class TestThread extends Thread
{
private int i;
private Semaphore semaphore;
public TestThread(int i, Semaphore semaphore)
{
this.i = i;
this.semaphore = semaphore;
}
public void run()
{
try
{
Thread.sleep(1000);
System.out.println("线程" + i + "结束");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
semaphore.release(); //每结束一个线程,释放一个信号量
}
}
public class TestCountDownLatch {
private Thread[] threads;
public TestCountDownLatch(final CountDownLatch sign, int n){
threads = new Thread[n];
for(int i=0;i<n;i++)
{
threads[i] = new Thread(new Runnable(){
@Override
public void run() {
System.out.println("work");
sign.countDown();
}
});
threads[i].start();
}
}
public static void main(String[] args) {
CountDownLatch sign = new CountDownLatch(10);
new TestCountDownLatch(sign, 10);
try {
sign.await();
System.out.println("Main exit");
} catch (InterruptedException e) {
e.printStackTrace();
}
}