synchronized关键字的作用(三)
synchronized的作用(三)
b、锁定一个对象或方法,它是静态的
这样锁定,它锁定的是对象所属的类
等同于
测试:
目标类:
线程类:调用不同的方法,于是建立了两个线程类
调用:
这样锁定,它锁定的是对象所属的类
- public <SPAN class=hilite1>synchronized</SPAN> static void execute(){
- //...
- }
等同于
- public class TestThread {
- public static void execute(){
- <SPAN class=hilite1>synchronized</SPAN>(TestThread.class){
- //
- }
- }
- }
测试:
目标类:
- public class TestThread {
- private static Object lock=new Object();
- public <SPAN class=hilite1>synchronized</SPAN> static void execute(){ //同步静态方法
- for(int i=0;i<100;i++){
- System.out.println(i);
- }
- }
- public static void execute1(){
- for(int i=0;i<100;i++){
- System.out.println(i);
- }
- }
- public void test(){
- execute(); //输出是有序的,说明是同步的
- //execute1(); //输出是无须的,说明是异步的
- }
- }
线程类:调用不同的方法,于是建立了两个线程类
- public class ThreadA implements Runnable{
- public void run() {
- TestThread.execute();//调用同步静态方法
- }
- }
- public class ThreadB implements Runnable{
- public void run() {
- TestThread test=new TestThread();
- test.test();//调用非同步非静态方法
- }
- }
调用:
- Runnable runabbleA=new ThreadA();
- Thread a=new Thread(runabbleA,"A");
- a.start();
- Runnable runabbleB=new ThreadB();
- Thread b=new Thread(runabbleB,"B");
- b.start();


浙公网安备 33010602011771号