【发布时间】:2021-05-04 00:28:41
【问题描述】:
//Initially, I wanted to compare synchronized with Lock
public class SynchronizedVSLock {
static final Lock lock = new ReentrantLock();
static final int loopTime = 10;
static final int numOfThread = 6;
static final Random random = new Random();
static final Semaphore runningThreadsNum = new Semaphore(numOfThread);
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
for (int i = 0; i < numOfThread - 1; i++) {
new Thread(new Test1()).start();
}
new Thread(new Test1()).join();
runningThreadsNum.acquire(numOfThread);
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
static class Test1 implements Runnable {
@Override
public void run() {
try {
runningThreadsNum.acquire();
} catch (InterruptedException e) {
throw new RuntimeException();
}
for (int i = 0; i < SynchronizedVSLock.loopTime; i++) {
SynchronizedVSLock.lock.lock();
System.out.println(SynchronizedVSLock.random.nextDouble());
SynchronizedVSLock.lock.unlock();
}
runningThreadsNum.release();
}
}
static class Test2 implements Runnable {
@Override
public void run() {
try {
runningThreadsNum.acquire();
} catch (InterruptedException e) {
throw new RuntimeException();
}
for (int i = 0; i < SynchronizedVSLock.loopTime; i++) {
synchronized (SynchronizedVSLock.lock) {
System.out.println(SynchronizedVSLock.random.nextDouble());
}
}
runningThreadsNum.release();
}
}
}
总体思路是创建多个线程并发执行输出随机数的任务,分别使用lock和synchronized两种同步机制。 最后将程序运行时间作为指标输出。 使用信号量确保主线程在所有子线程完成之前不会获得最终经过的时间 但是我发现很多时候主线程在其他子线程运行之前就拿到了所有的权限,然后打印出一个很小的运行时间,也就一两毫秒,不知道怎么回事。
【问题讨论】:
标签: java multithreading concurrency semaphore java.util.concurrent