首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java同步机制及synchronized关键字的施用2

2013-03-28 
java同步机制及synchronized关键字的应用2public class TestSynchronizedMethod {private void ivkMethod1

java同步机制及synchronized关键字的应用2
public class TestSynchronizedMethod {private void ivkMethod1(){Thread thread1 = new Thread() {public void run() {for(int i = 0; i < 20; i++) {//System.out.println("\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");//System.out.println("~~~~ start thread method1 ");method1();//System.out.println("~~~~ end thread method1 ");}}};thread1.start();}private void ivkMethod2(){Thread thread2 = new Thread() {public void run() {for(int i = 0; i < 20; i++) {//System.out.println("\n\n#################################################");//System.out.println("#### start thread method2 ");method2();//System.out.println("#### end thread method2 ");}}};thread2.start();}private synchronized void method1(){System.out.println("\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");System.out.println("~~~~ enter method1");try{System.out.println("~~~~ method1 begin to sleep 10s");Thread.sleep(10000);}catch(Exception e){e.printStackTrace();}System.out.println("~~~~ method1 end sleep");}private synchronized void method2(){System.out.println("\n\n#################################################");System.out.println("#### enter method2");try{System.out.println("#### method2 begin to sleep 3s");Thread.sleep(3000);}catch(Exception e){e.printStackTrace();}System.out.println("#### method2 end sleep");}/** * @param args */public static void main(String[] args) {try {TestSynchronizedMethod obj = new TestSynchronizedMethod();obj.ivkMethod1();obj.ivkMethod2();} catch (Exception e) {e.printStackTrace();} catch (Error er) {er.printStackTrace();}}}

?

结论很明显,无需多言。究其原因,method1和method2所持的锁为obj实例锁,所以当对同一obj调用两个方法时,两者不能并发执行。

?

1 楼 zengyan2012 2 小时前  

究其原因,method1和method2所持的锁为obj实例锁


是不是可以这么理解:
private synchronized void method2{

}
其实跟
private  void method2{
     synchronized(this){

   }
}

是一样的效果?

热点排行