synchronized关键字的作用(三)

synchronized的作用(三)

b、锁定一个对象或方法,它是静态的
这样锁定,它锁定的是对象所属的类
Java代码
  1. public <SPAN class=hilite1>synchronized</SPAN>    static void execute(){   
  2.       //...   
  3. }  


等同于

Java代码
  1. public class TestThread {   
  2.     public static void execute(){   
  3.         <SPAN class=hilite1>synchronized</SPAN>(TestThread.class){   
  4.             //   
  5.           }   
  6.       }   
  7. }  

测试:

目标类:

Java代码
  1. public class TestThread {   
  2.     private static Object lock=new Object();   
  3.     public <SPAN class=hilite1>synchronized</SPAN> static void execute(){  //同步静态方法   
  4.         for(int i=0;i<100;i++){   
  5.               System.out.println(i);   
  6.           }       
  7.       }   
  8.     public static void execute1(){   
  9.         for(int i=0;i<100;i++){   
  10.               System.out.println(i);   
  11.           }       
  12.       }   
  13.     public void test(){   
  14.           execute();     //输出是有序的,说明是同步的   
  15.         //execute1();  //输出是无须的,说明是异步的   
  16.       }   
  17. }  


线程类:调用不同的方法,于是建立了两个线程类


Java代码
  1. public class ThreadA implements Runnable{   
  2.     public void run() {   
  3.           TestThread.execute();//调用同步静态方法   
  4.       }   
  5. }   
  6. public class ThreadB implements Runnable{   
  7.     public void run() {   
  8.           TestThread test=new TestThread();   
  9.           test.test();//调用非同步非静态方法   
  10.       }   
  11. }  

调用:

Java代码
  1. Runnable runabbleA=new ThreadA();   
  2. Thread a=new Thread(runabbleA,"A");                   
  3. a.start();   
  4. Runnable runabbleB=new ThreadB();   
  5. Thread b=new Thread(runabbleB,"B");                   
  6. b.start();  

 

posted @ 2008-07-02 16:17  supers  阅读(156)  评论(0)    收藏  举报