1. 程式人生 > >多線程並發測試

多線程並發測試

long args ati tac start normal down generate lin

package main.java.com.crm.test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import main.java.com.crm.testScript.leads.NormalAssign;

public class LatchTest {


public static void main(String[] args) throws InterruptedException {
Runnable taskTemp = new Runnable() {


// 註意,此處是非線程安全的,留坑
private int iCounter;

@Override
public void run() {
for(int i = 0; i < 10; i++) {
// 發起請求
System.out.println("分配的銷售:"+i);
NormalAssign normalAssign = new NormalAssign();
try {
normalAssign.normalAssign("010", "100", "3", 1,1500L+i);
} catch (UnsupportedOperationException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
iCounter++;
System.out.println(System.nanoTime() + " [" + Thread.currentThread().getName() + "] iCounter = " + iCounter);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};

LatchTest latchTest = new LatchTest();
latchTest.startTaskAllInOnce(5, taskTemp);
}

public long startTaskAllInOnce(int threadNums, final Runnable task) throws InterruptedException {
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(threadNums);
for(int i = 0; i < threadNums; i++) {
Thread t = new Thread() {
public void run() {
try {
// 使線程在此等待,當開始門打開時,一起湧入門中
startGate.await();
try {
task.run();
} finally {
// 將結束門減1,減到0時,就可以開啟結束門了
endGate.countDown();
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
};
t.start();
}
long startTime = System.nanoTime();
System.out.println(startTime + " [" + Thread.currentThread() + "] All thread is ready, concurrent going...");
// 因開啟門只需一個開關,所以立馬就開啟開始門
startGate.countDown();
// 等等結束門開啟
endGate.await();
long endTime = System.nanoTime();
System.out.println(endTime + " [" + Thread.currentThread() + "] All thread is completed.");
return endTime - startTime;
}
}

多線程並發測試