关键字synchronized可以使多个线程访问同一个资源具有同步性,而且他还具有将线程工作内存中的私有变量与公共内存中的变量同步的功能。
package com.cky.thread; /** * Created by edison on 2017/12/9. */ public class Service { private boolean isContinueRun = true; public void runMethod() { while(isContinueRun == true) { } System.out.println("停下来了"); } public void stopMethod() { isContinueRun = false; } }
package com.cky.thread; /** * 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.runMethod(); } }
package com.cky.thread; /** * 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.stopMethod(); } }
package com.cky.test; import com.cky.thread.Service; import com.cky.thread.ThreadA; import com.cky.thread.ThreadB; /** * Created by edison on 2017/12/9. */ public class Run { public static void main(String[] args) { try { Service service = new Service(); ThreadA threadA = new ThreadA(service); threadA.start(); Thread.sleep(2000); ThreadB threadB = new ThreadB(service); threadB.start(); System.out.println("已经发起停止的命令"); } catch (InterruptedException e) { e.printStackTrace(); } } }
已经发起停止的命令
以-server服务器模式运行得到死循环
得到上面结果的原因是各个线程间的数据值没有可视性造成的。而关键字synchronized具有可视性。
更改Service.java代码
package com.cky.thread; /** * Created by edison on 2017/12/9. */ public class Service { private boolean isContinueRun = true; public void runMethod() { String anything =new String(); while(isContinueRun == true) { synchronized (anything) { } } System.out.println("停下来了"); } public void stopMethod() { isContinueRun = false; } }
已经发起停止的命令 停下来了
关键字synchronized可以保证在同一时刻,只有一个线程可以执行某一个方法或者某一个代码块
他包含了两个特性,互斥性和可见性,同步synchronized不仅可以解决一个线程看到的对象处于不一致的状态,还可以保证进入同步方法或者同步代码块的每个线程
都看到由同一个锁保护之前的修改效果。