In this chapter we continue to discuss another drawback of suspend and resume-out of sync.
1. Code Listing
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, St Ring 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 = MYOBJ ECT;} @Overridepublic void Run () {Myobject.set (1, "Ray");}} Class Threadtwo implements Runnable {private MyObject myobject;public threadtwo (MyObject MyObject) {this.myobject = MYOBJ ECT;} @Overridepublic void Run () {myobject.printstr ();}}
Output:
1 init
2. Explanation
Although the above example I think is still a little exact, but it does form the above we say the result, the data is out of sync.
Why not exact: if we adjust the waiting time between two methods (or call execution time) through the adjustment of time, it is possible that the above result will appear, of course, we pass the above code, is bound to appear this unsynchronized result. Therefore, personally think this example is a bit exact, if the reader has a better example, please tell
Summary: This chapter shows another drawback of suspend and resume-data is out of sync.
My github:https://github.com/raylee2015/deepintothread.
Understanding multithreading -1.12 Suspend and resume drawbacks from scratch-out of sync