考虑使用倒计时锁存器来实现最大并行度。基本上,您可以创建总计数为 1 的单例/静态 countdownLatch 并让多个线程等待相同的倒计时。检查下面我做了什么
指示线程开始时间的主线程。
package mylab.threads;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainThread extends TimerTask {
private static CountDownLatch countDown = new CountDownLatch(1);
private ExecutorService es = Executors.newCachedThreadPool();
@Override
public void run() {
try {
Thread1 thread1 = new Thread1();
thread1.setDoneSignal(countDown);
es.submit(thread1);
Thread2 thread2 = new Thread2();
thread2.setDoneSignal(countDown);
es.submit(thread2);
System.out.println("waiting main.. ");
synchronized(this) {
this.wait(2000);
}
System.out.println("kick off threads..");
countDown.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
定义要并行运行的线程
package mylab.threads;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
public class Thread1 extends TimerTask{
private CountDownLatch doneSignal = null;
/**
* @return the doneSignal
*/
public CountDownLatch getDoneSignal() {
return doneSignal;
}
/**
* @param doneSignal the doneSignal to set
*/
public void setDoneSignal(CountDownLatch doneSignal) {
this.doneSignal = doneSignal;
}
@Override
public void run() {
try {
this.doneSignal.await();
System.out.println("get going thread 1 -"+new Date().getTime());
synchronized(this) {
this.wait(3000);
}
System.out.println("Exiting thread 1 - "+new Date().getTime());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package mylab.threads;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
public class Thread2 extends TimerTask{
private CountDownLatch doneSignal = null;
/**
* @return the doneSignal
*/
public CountDownLatch getDoneSignal() {
return doneSignal;
}
/**
* @param doneSignal the doneSignal to set
*/
public void setDoneSignal(CountDownLatch doneSignal) {
this.doneSignal = doneSignal;
}
@Override
public void run() {
try {
this.doneSignal.await();
System.out.println("get going thread 2 -"+new Date().getTime());
synchronized(this) {
this.wait(3000);
}
System.out.println("Exiting thread 2 - "+new Date().getTime());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最后运行主线程。
package mylab.threads;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
MainThread mt = new MainThread();
mt.run();
}
}
这是输出
waiting main..
kick off threads..
get going thread 1 -1387513662107
get going thread 2 -1387513662107
Exiting thread 1 - 1387513665108
Exiting thread 2 - 1387513665108