今天看了下线程中ReentrantLock类,便根据网上的资料写了个测试代码?
结果发现每次运行速度都不一样很纳闷。。。。。特来求教--哪出问题了?
另外第一次特别慢许多?
ps:网上说 Tim Peierls 用一个简单的线性全等伪随机数生成器(PRNG)构建了一个简单的评测
哪位大虾有这评测,能否提供,感激不尽!
[code="java"]public class ReentrantLockTest {
private CyclicBarrier barrier;
private Object objTest;
private int threadNum;
public ReentrantLockTest(int threadNum) {
barrier = new CyclicBarrier(threadNum + 1);
this.threadNum = threadNum;
}
public static void main(String args[]) {
int threadCount = 5000;
ReentrantLockTest test4 = new ReentrantLockTest(threadCount);
test4.objTest = test4.new ReentrantLockUnFair();
test4.test();
ReentrantLockTest test2 = new ReentrantLockTest(threadCount);
test2.objTest = test2.new ReentrantLockUnFair();
test2.test();
ReentrantLockTest test1 = new ReentrantLockTest(threadCount);
test1.objTest = test1.new ReentrantLockFair();
test1.test();
ReentrantLockTest test3 = new ReentrantLockTest(threadCount);
test3.objTest = test3.new SynchronizedTest();
test3.test();
}
public void test() {
try {
for (int i = 0; i < threadNum; i++) {
new TestThread(objTest).start();
}
barrier.await(); // 等待所有任务线程创建
long start = System.currentTimeMillis();
barrier.await(); // 等待所有任务计算完成
long end = System.currentTimeMillis();
//另外一种写发
// long start = System.currentTimeMillis();
// barrier.await(); // 等待所有任务线程创建
// barrier.await(); // 等待所有任务计算完成
// long end = System.currentTimeMillis();
System.out.println("花费时间:" + (end - start) + "毫秒");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
class TestThread extends Thread {
private Object obj;
public TestThread(Object obj) {
this.obj = obj;
}
public void run() {
try {
barrier.await();
obj.equals("");
barrier.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class ReentrantLockFair {
public boolean equals(Object obj){
final Lock lock = new ReentrantLock(true);
lock.lock();
try {
for(int i=0 ; i<10 ; i++){
}
} finally {
lock.unlock();
}
return true;
}
}
class ReentrantLockUnFair {
public boolean equals(Object obj){
final Lock lock = new ReentrantLock(false);
lock.lock();
try {
for(int i=0 ; i<10 ; i++){
}
} finally {
lock.unlock();
}
return true;
}
}
class SynchronizedTest {
public boolean equals(Object obj){
synchronized (obj) {
for(int i=0 ; i<10 ; i++){
}
}
return true;
}
}
} [/code]
[b]问题补充:[/b]
个人练习,无需求。。。
弄不明白所以来求教,环境。。本机 :cry:
[b]问题补充:[/b]
把94行 synchronized (obj) { 改成了 synchronized (this)
每次测试都不一样,我就是按那篇修改来的
可测试结果每次不一样,请问我这样的测试类有问题吗?问题在哪呢?