在看《
《
分享下看书的心得把,我觉得写博客是很好的学习方式,不再拿书上的例子,例子全部为自己重写,这样才能引发更多的思考。
看下面这个例子,
这个类看似充分进行了同步?我想细心点的大家很容易就能发现其中的问题。
public class Plane {private int x = 1;private int y = 1;public synchronized int getX() {return x;}public synchronized int getY() {return y;}public void renderer() {System.out.println("飞机的X坐标"+ getX() + "飞机的Y坐标" + getY());}public synchronized void move1 () {x = 2;y = 2;}public synchronized void move2 () {x = 3;y = 3;}public static void main(String[] args) {Plane p = new Plane();new Dispatcher(p).start();new Renderer(p).start();}static class Dispatcher extends Thread {private Plane p;int i = 1;public Dispatcher(Plane p) {this.p = p;}@Overridepublic void run() {while (true) {if (i % 2 == 1) {p.move1();i++;} else {p.move2();i++;}}}}static class Renderer extends Thread {private Plane p;public Renderer(Plane p) {this.p = p;}@Overridepublic void run() {while (true) {p.renderer();}}}}
这个问题非常容易解释,在对获得锁,那么读取到后来修改的这个
public void renderer() {int _x;int _y;synchronized (this) {_x = getX();_y = getY();}System.out.println("飞机的X坐标"+ _x + "飞机的Y坐标" + _y);}
OK
现在可以引入
(1)同一个线程内的操作,源代码前面的操作一定会被后面的操作看到
如在主线程中
public static void main(String[] args) {int i = 0;i = 5;System.out.println(i);}
这就说
public class Five {private static float money = 0;private static boolean isObey = true;public static void main(String[] args) {new FiveCent().start();isObey = false;money = 0.5f;}static class FiveCent extends Thread {@Overridepublic void run() {while (!isObey) {Thread.yield();}System.out.println("社会主义好 == " + money);}}}
有可能
(2)同一个锁的unlockhappened-beforelock
(3)好了,有了这三条原则已经可以解释很多多线程问题了,现在结合这的问题。
首先,happened-beforeunlock。
然后,
有了基本的概念,下篇文章会说下如何构建线程安全的类。
,人若软弱就是自己最大的敌人