//本来我是想比较一下Synchronized和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();
}
}
}
这段java并发代码为啥经常不能正常运行?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
10条回答 默认 最新
- 纯白微风<alert> 2021-01-30 15:11关注
我看你代码你是想主线程通过调用其它线程的join()方法等其它线程执行完后再执行主线程,那你可以这样写:
for (int i = 0; i < numOfThread; i++) { Thread thread = new Thread(new Test1()); thread.start(); thread.join(); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 西门子S7-Graph,S7-300,梯形图
- ¥50 用易语言http 访问不了网页
- ¥50 safari浏览器fetch提交数据后数据丢失问题
- ¥15 matlab不知道怎么改,求解答!!
- ¥15 永磁直线电机的电流环pi调不出来
- ¥15 用stata实现聚类的代码
- ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
- ¥20 docker里部署springboot项目,访问不到扬声器
- ¥15 netty整合springboot之后自动重连失效
- ¥15 悬赏!微信开发者工具报错,求帮改