2.2.11同步synchronized方法无限等待与解决
Posted 成功的路上总是离不开贵人的帮助,名师的指点和小人的刺激。
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.2.11同步synchronized方法无限等待与解决相关的知识,希望对你有一定的参考价值。
同步方法容易造成死循环。
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
运行结果不再出现同步等待的情况。
以上是关于2.2.11同步synchronized方法无限等待与解决的主要内容,如果未能解决你的问题,请参考以下文章
Java并发编程专题系列之深入分析synchronized(基础篇)
进程同步 (Process Synchronization)