Java中使用synchronized和Lock对象获取对象锁 - 编程入门网
ck对象获取对象锁(2)
时间:2011-01-25 zhangjunhd
结果: Thread-0:not synchronized in f() Thread-0:synchronized in f() main:not synchronized in h() Thread-1:not synchronized in g() Thread-0:synchronized in f() Thread-0:synchronized in f() Thread-0:synchronized in f() Thread-0:synchronized in f() Thread-1:synchronized in g() Thread-1:synchronized in g() Thread-1:synchronized in g() Thread-1:synchronized in g() Thread-1:synchronized in g() main:synchronized in h() main:synchronized in h() main:synchronized in h() main:synchronized in h() main:synchronized in h() Java中使用synchronized和Lock对象获取对象锁(3)时间:2011-01-25 zhangjunhd2.2 同步到多个对象锁 Resource1.java演示了三个线程(包括main线程)试图进入某个类的三个不同的方法的同步块中,这些同步块处在不同的方法中,并且是同步到三个不同的对象(synchronized (this),synchronized (syncObject1),synchronized (syncObject2)),所以对它们的方法中的临界资源访问是独立的。 Resource2.java package com.zj.lock;import java.util.concurrent.TimeUnit; public class Resource2 { private Object syncObject1 = new Object(); private Object syncObject2 = new Object(); public void f() { // other operations should not be locked... System.out.println(Thread.currentThread().getName() + ":not synchronized in f()"); synchronized (this) { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + ":synchronized in f()"); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } } } } public void g() { // other operations should not be locked... System.out.println(Thread.currentThread().getName() + ":not synchronized in g()"); synchronized (syncObject1) { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + ":synchronized in g()"); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } } } } public void h() { // other operations should not be locked... System.out.println(Thread.currentThread().getName() + ":not synchronized in h()"); synchronized (syncObject2) { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + ":synchronized in h()"); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { final Resource2 rs = new Resource2(); new Thread() { public void run() { |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |