这个可以有2种解决方案,notify,wait实现 以及CountDownLatch,
我贴一个CountDownLatch的实现
public class Test4 {
class DTask implements Runnable
{
private CountDownLatch downLatch;
private String name;
public DTask(CountDownLatch downLatch,String name)
{
this.downLatch =downLatch;
this.name =name;
}
public void run()
{
if(name.equals("A"))
try {
this.downLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+"====>"+i);
}
//if(name.equals("B"))
this.downLatch.countDown();
}
}
public static void test1()
{
ExecutorService service =Executors.newFixedThreadPool(2);
Object obj =new Object();
Test4 tt =new Test4();
CountDownLatch downLatch = new CountDownLatch(1);
service.execute(tt.new DTask(downLatch,"A") );
service.execute(tt.new DTask(downLatch,"B") );
service.shutdown();
}
public static void main(String[] args)
{
test1();
}
}
2012年9月24日 17:15