📄 semaphore.java
字号:
package net.betterjava.sample.xml.bind.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class Semaphore {
private int READY_NUM = 5;
private int threadCounter = 0;
private long elapseTime = 0;
private int round;
private String testFileName = "data.";
private int testFileCount = 10;
private String[] rawData = new String[10];
private int[] inputData;
private int nextInputData;
public synchronized void elapse(long time) {
elapseTime += time;
}
public Semaphore(int aReadyNum, int aRound) throws IOException {
READY_NUM = aReadyNum;
round = aRound;
generateInputData();
}
private String readTestString(String fileName) throws IOException {
FileReader reader = new FileReader(fileName);
BufferedReader bfReader = new BufferedReader(reader);
StringBuffer sampleSB = new StringBuffer();
String lineStr = bfReader.readLine();
while (lineStr != null) {
sampleSB.append(lineStr + "\n");
lineStr = bfReader.readLine();
}
return sampleSB.toString();
}
private void generateInputData() throws IOException {
for (int i = 0; i < testFileCount; i++) {
rawData[i] = readTestString(testFileName + i);
}
inputData = new int[round];
for (int i = 0; i < round; i++) {
double d = Math.random();
int index = ((int) (d * 10)) % testFileCount;
//System.out.println(index);
inputData[i] = index;
}
}
public synchronized String nextInput() {
return rawData[inputData[nextInputData++]];
}
public boolean hasNext() {
return nextInputData != inputData.length;
}
public void waitAllReady() {
if (threadCounter == READY_NUM) {
return;
}
synchronized (this) {
threadCounter++;
if (threadCounter < READY_NUM) {
try {
wait();
} catch (InterruptedException exp) {
System.out.println("interrupted exception in Semaphore");
}
} else
notifyAll();
System.out.println(
Thread.currentThread() + " start at " + System.currentTimeMillis());
}
}
public long getElapseTime() {
return elapseTime;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -