开发学院软件开发Java Java 多线程同步问题的探究(三、Lock来了,大家都... 阅读

Java 多线程同步问题的探究(三、Lock来了,大家都让开【1. 认识重入锁】)

 2010-05-14 00:00:00 来源:WEB开发网   
核心提示: 运行结果:aisrunning!agotlock1@Step1!bisrunning!cisrunning!afirstReadingcount:1areleaselock1@Step1!agotlock2@Step2!threadasetageto:76threadafirstreadagei

运行结果:

a is running!
a got lock1@Step1!
b is running!
c is running!
a first Reading count:1
a release lock1@Step1!
a got lock2@Step2!
thread a set age to:76
thread a first  read age is:76
thread a second read age is:76
a release lock2@Step2!
c got lock1@Step1!
c first Reading count:2
c release lock1@Step1!
c got lock2@Step2!
thread c set age to:35
thread c first  read age is:35
thread c second read age is:35
c release lock2@Step2!
b got lock1@Step1!
b first Reading count:3
b release lock1@Step1!
b got lock2@Step2!
thread b set age to:91
thread b first  read age is:91
thread b second read age is:91
b release lock2@Step2!
成功生成(总时间:30 秒)

显然,在这个程序中,由于两段synchronized块使用了同样的对象做为对象锁,所以JVM优先使刚刚释放该锁的线程重新获得该锁。这样,每个线程执行的时间是10秒钟,并且要彻底把两个同步块的动作执行完毕,才能释放对象锁。这样,加起来一共是 30秒。

我想一定有人会说:如果两段synchronized块采用两个不同的对象锁,就可以提高程序的并发性,并且,这两个对象锁应该选择那些被所有线程所共享的对象。

那么好。我们把第二个同步块中的对象锁改为student(此处略去代码,读者自己修改),程序运行结果为:

a is running!
a got lock1@Step1!
b is running!
c is running!
a first Reading count:1
a release lock1@Step1!
a got lock2@Step2!
thread a set age to:73
thread a first  read age is:73
c got lock1@Step1!
thread a second read age is:73
a release lock2@Step2!
c first Reading count:2
c release lock1@Step1!
c got lock2@Step2!
thread c set age to:15
thread c first  read age is:15
b got lock1@Step1!
thread c second read age is:15
c release lock2@Step2!
b first Reading count:3
b release lock1@Step1!
b got lock2@Step2!
thread b set age to:19
thread b first  read age is:19
thread b second read age is:19
b release lock2@Step2!
成功生成(总时间:21 秒)

上一页  1 2 3 4  下一页

Tags:Java 线程 同步

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接