同步方法容易造成死循环。
package com.cky.bean; /** * Created by edison on 2017/12/8. */ public class Service { synchronized public void methodA(){ System.out.println("methodA begin"); boolean isContinueRun = true; while (isContinueRun) { } System.out.println("methodA end"); } synchronized public void methodB(){ System.out.println("methodB begin"); System.out.println("methodB end"); } }
package com.cky.thread; import com.cky.bean.Service; /** * Created by edison on 2017/12/8. */ public class ThreadA extends Thread{ private Service service; public ThreadA(Service service) { this.service = service; } @Override public void run() { super.run(); service.methodA(); } }
package com.cky.thread; import com.cky.bean.Service; /** * Created by edison on 2017/12/8. */ public class ThreadB extends Thread{ private Service service; public ThreadB(Service service) { this.service = service; } @Override public void run() { super.run(); service.methodB(); } }
package com.cky.test; import com.cky.bean.Service; import com.cky.thread.ThreadA; import com.cky.thread.ThreadB; /** * Created by edison on 2017/12/8. */ public class Test { public static void main(String[] args) { Service service = new Service(); ThreadA threadA = new ThreadA(service); threadA.setName("a"); threadA.start(); ThreadB threadB = new ThreadB(service); threadB.setName("b"); threadB.start(); } }
methodA begin
Process finished with exit code 1
结果运行:
线程B永远得不到运行的机会,锁死了。
这时可以使用同步代码块来解决这样的问题
更改Service.java文件代码
package com.cky.bean; /** * Created by edison on 2017/12/8. */ public class Service { Object object1 = new Object(); public void methodA(){ synchronized (object1) { System.out.println("methodA begin"); boolean isContinueRun = true; while (isContinueRun) { } System.out.println("methodA end"); } } Object object2 = new Object(); public void methodB(){ synchronized (object2) { System.out.println("methodB begin"); System.out.println("methodB end"); } } }
methodA begin
methodB begin
methodB end
运行结果不再出现同步等待的情况。