Understanding multithreading -1.12 Suspend and resume drawbacks from scratch-out of sync

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.