マルチスレッド同時テストクラス
1760 ワード
同時実行のマルチスレッドテストクラステンプレート:
package test;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
public class MultithreadTest {
final int count = 250;
static long beginTime;
class MyThread implements Runnable {
private CountDownLatch latch;
private CyclicBarrier barrier;
public MyThread(CountDownLatch latch,CyclicBarrier barrier){
this.latch = latch;
this.barrier = barrier;
}
@Override
public void run() {
try {
barrier.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (BrokenBarrierException e1) {
e1.printStackTrace();
}
new Thread(new TaskAlarm(latch)).start();
}
}
class TaskAlarm implements Runnable{
private CountDownLatch latch;
public TaskAlarm(CountDownLatch latch){
this.latch = latch;
}
@Override
public void run() {
for(int i=0;i<20;i++){
// 。。。。
}
System.out.println(Thread.currentThread().getName()+":, :"+(System.currentTimeMillis()-beginTime)+"ms");
latch.countDown();
}
}
private void runThread() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(count);
CyclicBarrier barrier = new CyclicBarrier(count);
for (int i = 0; i < count; i++) {
Thread tt = new Thread(new MyThread(latch,barrier));
tt.start();
}
latch.await();
System.out.println(" :"+(System.currentTimeMillis()-beginTime));
}
/**
* @param args
*/
public static void main(String[] args) {
beginTime = System.currentTimeMillis();
try {
new MultithreadTest().runThread();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}