标签:
这一章节我们继续来讨论suspend和resume的另一个缺点-不同步。
1.代码清单
package com.ray.deepintothread.ch01.topic_12; public class SuspendUnSynch { public static void main(String[] args) throws InterruptedException { MyObject myObject = new MyObject(); ThreadOne threadOne = new ThreadOne(myObject); Thread thread = new Thread(threadOne); thread.start(); ThreadTwo threadTwo = new ThreadTwo(myObject); Thread thread2 = new Thread(threadTwo); thread2.start(); } } class MyObject { private int id = 0; private String name = "init"; @SuppressWarnings("deprecation") public void set(int id, String name) { this.id = id; Thread.currentThread().suspend(); this.name = name; } public void printStr() { System.out.println(id + " " + name); } } class ThreadOne implements Runnable { private MyObject myObject; public ThreadOne(MyObject myObject) { this.myObject = myObject; } @Override public void run() { myObject.set(1, "ray"); } } class ThreadTwo implements Runnable { private MyObject myObject; public ThreadTwo(MyObject myObject) { this.myObject = myObject; } @Override public void run() { myObject.printStr(); } }
1 init
2.解释
虽然上面的例子笔者觉得还是有点不切当,但是它确实形成了上面我们所说的结果,数据不同步。
不切当的原因:如果我们通过时间的调整,把两个方法之间的等待时间(或者叫执行时间)调整一下,有可能就会出现上面的结果,当然,我们通过上面的代码,是必然会出现这个不同步的结果。因此,个人觉得这个例子有点不切当,如果读者有更好的例子,请告知
总结:这一章节展示了suspend和resume的另一个缺点-数据不同步。
我的github:https://github.com/raylee2015/DeepIntoThread
从头认识多线程-1.12 suspend和resume缺点-不同步
标签:
原文地址:http://blog.csdn.net/raylee2007/article/details/51178330