最大の並列処理を実現するために、カウントダウン ラッチの使用を検討してください。基本的に、合計カウント 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