本例说明:不在同步代码块的是异步执行,在同步代码块时同步的
package com.cky.bean; /** * Created by chenkaiyang on 2017/12/6. */ public class ObjectService { public void serviceMethodA(){ for (int i = 0; i < 100; i++) { System.out.println("no同步"+ Thread.currentThread().getName() +" i="+(i+1)); } System.out.println(""); synchronized (this) { for (int i = 0; i < 100; i++) { System.out.println("同步"+ Thread.currentThread().getName() +" i="+(i+1)); } } } }
package com.cky.thread; import com.cky.bean.ObjectService; /** * Created by chenkaiyang on 2017/12/5. */ public class ThreadA extends Thread{ private ObjectService service; public ThreadA(ObjectService service) { super(); this.service = service; } @Override public void run() { super.run(); service.serviceMethodA(); } }
package com.cky.thread; import com.cky.bean.ObjectService; /** * Created by chenkaiyang on 2017/12/5. */ public class ThreadB extends Thread{ private ObjectService service; public ThreadB(ObjectService service) { super(); this.service = service; } @Override public void run() { super.run(); service.serviceMethodA(); } }
package com.cky.test; import com.cky.bean.ObjectService; import com.cky.thread.ThreadA; import com.cky.thread.ThreadB; /** * Created by chenkaiyang on 2017/12/6. */ public class Test2 { public static void main(String[] args) { ObjectService objectService = new ObjectService(); ThreadA a = new ThreadA(objectService); a.setName("a"); ThreadB b = new ThreadB(objectService); b.setName("b"); a.start(); b.start(); } }
no同步a i=1 no同步b i=1 no同步b i=2 no同步b i=3 no同步b i=4 no同步b i=5 no同步b i=6 no同步b i=7 no同步b i=8
同步b i=1 同步b i=2 同步b i=3 同步b i=4 同步b i=5 同步b i=6 同步b i=7 同步b i=8 同步b i=9 同步b i=10
结果可知:同步代码块的代码是排队执行的,而非同步代码块是异步执行的。